IXmlSerializable, reading xml tree with many nested elements

萝らか妹 提交于 2019-12-11 07:38:34

问题


Could you guys give me an example how to read and write from/to xml like this:

<Foolist>
   <Foo name="A">
     <Child name="Child 1"/>
     <Child name="Child 2"/>
   </Foo> 
   <Foo name = "B"/>
   <Foo name = "C">
     <Child name="Child 1">
       <Grandchild name ="Little 1"/>
     </Child>
   </Foo>
<Foolist>

回答1:


Does the element name really change per level? If not, you can use a very simple class model and XmlSerializer. Implementing IXmlSerializable is... tricky; and error-prone. Avoid it unless you absolutely have to use it.

If the names are different but rigid, I'd just run it through xsd:

xsd example.xml
xsd example.xsd /classes

For an XmlSerializer without IXmlSerializable example (same names at each level):

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot("Foolist")]
public class Record
{
    public Record(string name)
        : this()
    {
        Name = name;
    }
    public Record() { Children = new List<Record>(); }
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlElement("Child")]
    public List<Record> Children { get; set; }
}

static class Program
{
    static void Main()
    {
        Record root = new Record {
            Children = {
                new Record("A") {
                    Children = {
                        new Record("Child 1"),
                        new Record("Child 2"),
                    }
                }, new Record("B"),
                new Record("C") {
                    Children = {
                        new Record("Child 1") {
                            Children = {
                                new Record("Little 1")
                            }
                        }
                    }
                }}
            };
        var ser = new XmlSerializer(typeof(Record));
        ser.Serialize(Console.Out, root);
    }
}


来源:https://stackoverflow.com/questions/1050839/ixmlserializable-reading-xml-tree-with-many-nested-elements

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