【发布时间】:2013-05-20 07:01:40
【问题描述】:
我想从具有嵌套对象的对象中创建一个包含嵌套元素的 xml 文档,但 xml 文件过于扁平。我怎样才能让它迭代对象中的对象以在元素中创建元素。
public object traverse(object pc, string xpath, XmlDocument xmldoc)
{
IEnumerable enumerable = pc as IEnumerable;
if (enumerable != null)
{
foreach (object element in enumerable)
{
RecurseObject ro = new RecurseObject();
ro.traverse(elementArray, xpath, xmldoc);
}
}
else
{
Type arrtype = pc.GetType();
string elementname = arrtype.Name;
foreach (var prop in pc.GetType().GetProperties())
{
XmlElement xmlfolder = null;
XmlNode xmlnode3 = null;
string propname = prop.Name;
string propvalue = "null";
if (xmldoc.SelectSingleNode(xpath + "/" + elementname) == null)
{
xmlnode3 = xmldoc.SelectSingleNode(xpath);
xmlfolder = xmldoc.CreateElement(null, elementname, null);
xmlnode3.AppendChild(xmlfolder);
}
if (prop.GetValue(pc, null) != null)
{
propvalue = prop.GetValue(pc, null).ToString();
}
xmlnode3 = xmldoc.SelectSingleNode(xpath + "/" + elementname);
xmlfolder = xmldoc.CreateElement(null, propname, null);
xmlfolder.InnerText = propvalue;
xmlnode3.AppendChild(xmlfolder);
}
}
return null;
}
【问题讨论】:
-
a)你的复杂对象怎么样b)最后你想得到什么样的xmlc) 你读过关于 xml 序列化的任何东西吗?
-
即使在格式化代码之后,也不清楚您到底想要实现什么。添加输入数据和所需输出的示例。
-
I4V 是对的。您可以通过序列化从对象自动生成 XML