Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize list to XML without parent element

Tags:

c#

.net

xml

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.

like image 675
xx77aBs Avatar asked Nov 20 '13 09:11

xx77aBs


1 Answers

Try

[XmlElement("ListItem")]
public List<ListItem> ListItems { get; set; }
like image 102
Maxim Zabolotskikh Avatar answered Oct 21 '22 23:10

Maxim Zabolotskikh