简体   繁体   English

如何在没有父元素的情况下将列表序列化为XML

[英]How to serialize list to XML without parent element

I'm using System.Xml.Serialization.XmlSerializer to serialize my class into a XML document. 我正在使用System.Xml.Serialization.XmlSerializer将我的类序列化为XML文档。 These are my classes: 这些是我的课程:

public class Test
{
    public List<ListItem> ListItems { get; set; }
    [XmlAttribute]
    public String Name { get; set; }
    [XmlAttribute]
    public String ID { get; set; }

    public Scenario()
    {
        this.ListItems = new List<ListItem>();
    }
}

public class ListItem
{
    public String Name { get; set; }
}

and this is the XML that I get: 这是我得到的XML:

<?xml version="1.0"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ListItems>
    <ListItem>
      <Name>test1</Name>
    </ListItem>
    <ListItem>
      <Name>test2</Name>
    </ListItem>
  </ListItems>
</Test>

Is it possible to get XML like this: 是否可以像这样获取XML:

<?xml version="1.0"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ListItem>
    <Name>test1</Name>
  </ListItem>
  <ListItem>
    <Name>test2</Name>
  </ListItem>
</Test>

Notice that in second Xml example (the one that I need to generate) ListItem nodes do not have parent ListItems node. 请注意,在第二个Xml示例(我需要生成的示例)中, ListItem节点没有父ListItems节点。

Try 尝试

[XmlElement("ListItem")]
public List<ListItem> ListItems { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM