本文介绍了IXmlSerializable,读取带有许多嵌套元素的 xml 树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们能给我一个例子,如何像这样从/向 xml 读取和写入:

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>

推荐答案

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

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.

如果名称不同但很严格,我会通过 xsd 运行它:

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

xsd example.xml
xsd example.xsd /classes

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

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

这篇关于IXmlSerializable,读取带有许多嵌套元素的 xml 树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 20:31