【问题标题】:How do I rename the root node when serialising a List<object> to XML in .NET?在 .NET 中将 List<object> 序列化为 XML 时如何重命名根节点?
【发布时间】:2016-11-03 23:09:59
【问题描述】:

我将美国州列表序列化为 XML,虽然我可以使用属性控制大多数输出​​元素的名称,但根节点始终称为“ArrayOfStates”。有没有办法改变它,所以它只是“状态”?

代码:

    public class Program
    {
        [XmlArray("States")]
        public static List<State> States;

        public static void Main(string[] args)
        {
            PopulateListOfStates();

            var xml = new XmlSerializer(typeof(List<State>));
            xml.Serialize(new XmlTextWriter(@"C:\output.xml",Encoding.Default), States);
        }
    }

    public struct State
    {
        [XmlAttribute]
        public string Name;

        [XmlArray("Neighbours")]
        [XmlArrayItem("Neighbour")]
        public List<string> Neighbours;
    }

输出:

<?xml version="1.0" encoding="Windows-1252"?>
<ArrayOfState xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <State Name="AL">
        <Neighbours>
            <Neighbour>FL</Neighbour>
            <Neighbour>GA</Neighbour>
            <Neighbour>MS</Neighbour>
            <Neighbour>TN</Neighbour>
        </Neighbours>
    </State>
    <State Name="FL">
        <Neighbours>
            <Neighbour>AL</Neighbour>
            <Neighbour>GA</Neighbour>
        </Neighbours>
    </State>
    <State Name="GA">
        <Neighbours>
            <Neighbour>AL</Neighbour>
            <Neighbour>FL</Neighbour>
            <Neighbour>NC</Neighbour>
            <Neighbour>SC</Neighbour>
            <Neighbour>TN</Neighbour>
        </Neighbours>
    </State>
    ...
</ArrayOfState>

顺便说一句,是否也可以将“邻居”元素的内容作为这些元素的属性(即&lt;Neighbour name="XX"/&gt;)?

【问题讨论】:

  • 创建一个包装器根对象,如此答案:Read XML file properly c# linq。或者覆盖根元素名称,如this answer 所示。但是,如果您使用第二个答案,则必须将序列化程序缓存在静态中,如here 所述。

标签: c# .net xml serialization attributes


【解决方案1】:
[Serializable]
public class Worksheet
{
    [XmlRoot(ElementName = "XML")]
    public class XML
    {
        [XmlArray("States")]
        public List<State> States { get; set; }
    }

    public class State
    {
        [XmlAttribute]
        public string Name { get; set; }

        [XmlArray("Neighbours")]
        [XmlArrayItem("Neighbour")]
        public List<Neighbour> Neighbours { get; set; }
    }

    public class Neighbour
    {
        [XmlAttribute]
        public string Name { get; set; }
    }
}

public static void Main(string[] args)
{
    Worksheet.XML xml = PopulateListOfStates();

    XmlSerializer serializer = new XmlSerializer(typeof(Worksheet.XML));
    using (StreamWriter writer = new StreamWriter(@"C:\output.xml", false))
    {
        serializer.Serialize(writer, xml);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多