序列化List时如何重命名根节点?在.net中转换为XML

本文关键字:net 转换 XML 根节点 重命名 object List 序列化 | 更新日期: 2023-09-27 18:16:09

我正在将美国各州的列表序列化为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>

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

序列化List<object>时如何重命名根节点?在.net中转换为XML

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