IXmlSerializable,读取包含许多嵌套元素的xml树

时间:2009-06-26 19:33:35

标签: c# xml-serialization ixmlserializable

你们能举个例子来说明如何从/向xml读取和写入:

<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 个答案:

答案 0 :(得分:2)

每个级别的元素名称是否真的改变了?如果没有,您可以使用一个非常简单的类模型和XmlSerializer。实施IXmlSerializable是......棘手的;并且容易出错。除非你绝对必须使用它,否则请避免使用它。

如果名称不同但很严格,我只需通过xsd:

运行它
xsd example.xml
xsd example.xsd /classes

对于没有XmlSerializer示例的IXmlSerializable(每个级别的名称相同):

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