你们能举个例子来说明如何从/向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>
答案 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);
}
}