我正在将美国各州列表序列化为 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”元素的内容作为这些元素的属性(即 <Neighbour name="XX"/>
)?
最佳答案
[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);
}
}
关于c# - 在 .NET 中将 List<object> 序列化为 XML 时如何重命名根节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412747/