我想从具有嵌套对象的对象创建一个包含嵌套元素的 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;
}