如何XmlSerializing数组时设定根节点的名字吗?数组、节点、名字、XmlSerializing

2023-09-03 15:53:41 作者:打着灯笼找媳妇i

我有我想序列化为XML对象的数组。这些对象注释设置XML节点的名字,但我不知道如何设置XML根节点的名称。

I have an array of objects which I want to serialize as XML. These objects are annotated to set XML node names but I was wondering how to set the name of the XML root node.

在code是这样的:

// create list of items
List<ListItem> list = new List<ListItem>();
list.Add(new ListItem("A1", new Location(1, 2)));
list.Add(new ListItem("A2", new Location(2, 3)));
list.Add(new ListItem("A3", new Location(3, 4)));
list.Add(new ListItem("A4<&xyz>", new Location()));

// serialise
XmlSerializer ser = new XmlSerializer(typeof(ListItem[]));
FileStream os = new FileStream(@"d:\temp\seri.xml", FileMode.Create);
ser.Serialize(os, list.ToArray());
os.Close();

输出看起来是这样的:

The output looks like this:

<?xml version="1.0"?>
<ArrayOfPlace xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Place>
    <Placename>A1</Placename>
    <Location>
      <Lat>1</Lat>
      <Long>2</Long>
    </Location>
  </Place>
  <Place>
  ...

列表项已更名为地点使用的的XmlElement 的注释,但如何设置根节点的名称重命名< STRONG>ArrayOfPlace节点?

ListItem has been renamed to Place using an XmlElement annotation, but how can I set the name of the root node to rename the 'ArrayOfPlace' node?

推荐答案

试试这个:

XmlSerializer ser = new XmlSerializer(
    typeof(ListItem[]), 
    new XmlRootAttribute("CustomRootName"));