【发布时间】:2016-03-23 12:38:22
【问题描述】:
我有一个“School”类,它嵌套了“Student”类,“name”作为“Student”的属性。
public class school
{
private List<student> mystudents;
public class student
{
private string name;
}
}
一所学校有很多学生,每个学生都有一个名字。
我有一个 XML 文档:
<school>
<student>
<name>John</name>
</student>
<student>
<name>Jane</name>
</student>
<student>
<name>Jack</name>
</student>
</school>
比方说,我创建了一个学校对象并想将此 xml 读入学校对象,我该怎么做?
我已经编写了将 XML 读入对象的工作代码,递归地将值复制到所有属性。我不知道如何为List<T> 即通用列表进行这项工作
下面是我递归读取 XML 到通用对象的代码:
/*----------------------------------------------------------------
' Template to read XML document into a Objects
'-----------------------------------------------------------------*/
public static T XmlToObject<T>(string fileName, T obj)
{
// read XML
string xmlString = File.ReadAllText(fileName);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString);
// read the root node
XmlNode groupsListNode = xmlDocument.GetElementsByTagName(obj.GetType().Name).Item(0);
// iterate through and copy values
XmlNodeToListProperties(groupsListNode, obj);
return obj;
}
public static void XmlNodeToProperties( XmlNode listNode, object obj)
{
//iterate through properties of object and copy from listNode
foreach(var prop in obj.GetType().GetProperties())
{
if (listNode[prop.Name] != null)
{
if (listNode[prop.Name].ChildNodes.Count > 1) // has child-properties
{
// call recursively
XmlNodeToProperties(listNode[prop.Name], prop.GetValue(obj, null));
}
else // no child properties
{
// get proprty type
Type t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
// convert listNode.FirstChild.value to PropertyType
object safeValue = CustomConvert( listNode[prop.Name], t) ;
// store in object
prop.SetValue(obj, safeValue, null);
}
}
我确实想过使用serializers,但问题是每个属性都需要xmlElement("name")。我的几个对象/类来自第三方 API,我无权编辑他们的类文件以插入 `xmlElement("name")。有关修改/更改上述通用模板以适应通用列表的任何建议?
【问题讨论】:
标签: c# .net xml visual-studio