【发布时间】: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>
顺便说一句,是否也可以将“邻居”元素的内容作为这些元素的属性(即<Neighbour name="XX"/>)?
【问题讨论】:
-
创建一个包装器根对象,如此答案:Read XML file properly c# linq。或者覆盖根元素名称,如this answer 所示。但是,如果您使用第二个答案,则必须将序列化程序缓存在静态中,如here 所述。
标签: c# .net xml serialization attributes