Reputation: 21
I'd like to created an xml document with nested elements from an object with nested objects but the xml file comes out too flat. How can I get this to iterate the objects within objects to create elements within elements.
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;
}
Upvotes: 1
Views: 888
Reputation: 9474
As mentioned in the comments, be aware that .NET includes the capability to convert object graphs to XML without you having to write any of the code to generate the XML. This process is referred to as serialization, and it should be easy to find examples online or here at SO.
If you prefer complete control over the process and wish to use reflection, Fasterflect includes code to convert an object graph to XML. It's a library with helpers to make reflection easier and faster. You can find the code for the XML extensions in this source file. Be aware that the referenced implementation does detect or handle circular references, whereas the built-in serialization mechanisms do.
As for your own solution, you do not seem to have any code to detect whether a property value is itself an object or a primitive value. You need to call your traverse method recursively also for object properties in order to process the entire object graph.
Upvotes: 1