简体   繁体   中英

How to serialize list to XML without parent element

I'm using System.Xml.Serialization.XmlSerializer to serialize my class into a XML document. 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 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 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.

Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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