How to create XML document from nested objects?

孤者浪人 提交于 2020-01-16 02:34:08

问题


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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/16640148/how-to-create-xml-document-from-nested-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!