代码之家  ›  专栏  ›  技术社区  ›  paul

在XmlSerialization数组时,如何设置根节点名称?

  •  18
  • paul  · 技术社区  · 16 年前

    // 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();
    

    <?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>
      ...
    

    列表项目 已重命名为 地方 注释,但如何设置根节点的名称以重命名

    3 回复  |  直到 16 年前
        1
  •  28
  •   Darin Dimitrov    16 年前

    试试这个:

    XmlSerializer ser = new XmlSerializer(
        typeof(ListItem[]), 
        new XmlRootAttribute("CustomRootName"));
    
        2
  •  3
  •   Will    16 年前

    使用 XmlRoot 属性。

        3
  •  0
  •   paul    16 年前

    我自己也找到了解决办法。

    XmlSerializer ser = new XmlSerializer(typeof(ListItem[]), new XmlRootAttribute("AllPlaces"));
    
    推荐文章