18

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.

The code looks like this:

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

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?

alexandrul
  • 12,856
  • 13
  • 72
  • 99
paul
  • 13,312
  • 23
  • 81
  • 144

3 Answers3

28

Try this:

XmlSerializer ser = new XmlSerializer(
    typeof(ListItem[]), 
    new XmlRootAttribute("CustomRootName"));
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Do note that it is necessary to cache the serializer for reuse later, otherwise one will have a severe memory leak. See [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer/) – dbc Nov 02 '16 at 23:00
3

Use the XmlRoot attribute.

0

Just found a solution myself as well.

It is possible to set the name of the root node when instantiating XmlSerializer. See below.

XmlSerializer ser = new XmlSerializer(typeof(ListItem[]), new XmlRootAttribute("AllPlaces"));
paul
  • 13,312
  • 23
  • 81
  • 144