c# - How to create XML document from nested objects? -
i'd created xml document nested elements object nested objects xml file comes out flat. how can iterate objects within objects create elements within elements.
public object traverse(object pc, string xpath, xmldocument xmldoc) { ienumerable enumerable = pc 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; }
as mentioned in comments, aware .net includes capability convert object graphs xml without having write of code generate xml. process referred serialization, , should easy find examples online or here @ so.
if prefer complete control on process , wish use reflection, fasterflect includes code convert object graph xml. it's library helpers make reflection easier , faster. can find code xml extensions in this source file. aware referenced implementation detect or handle circular references, whereas built-in serialization mechanisms do.
as own solution, not seem have code detect whether property value object or primitive value. need call traverse method recursively object properties in order process entire object graph.
Comments
Post a Comment