DisplayName
DisplayName

Reputation: 541

How do I rename the root node when serialising a List<object> to XML in .NET?

I am serialising a List of US States into XML, and while I can control the names of most of the output elements with attributes, the root node is always called "ArrayOfStates". Is there a way to change this so it is just "States"?

Code:

    public class Program
    {
        [XmlArray("States")]
        public static List<State> States;

        public static void Main(string[] args)
        {
            PopulateListOfStates();

            var xml = new XmlSerializer(typeof(List<State>));
            xml.Serialize(new XmlTextWriter(@"C:\output.xml",Encoding.Default), States);
        }
    }

    public struct State
    {
        [XmlAttribute]
        public string Name;

        [XmlArray("Neighbours")]
        [XmlArrayItem("Neighbour")]
        public List<string> Neighbours;
    }

Output:

<?xml version="1.0" encoding="Windows-1252"?>
<ArrayOfState xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <State Name="AL">
        <Neighbours>
            <Neighbour>FL</Neighbour>
            <Neighbour>GA</Neighbour>
            <Neighbour>MS</Neighbour>
            <Neighbour>TN</Neighbour>
        </Neighbours>
    </State>
    <State Name="FL">
        <Neighbours>
            <Neighbour>AL</Neighbour>
            <Neighbour>GA</Neighbour>
        </Neighbours>
    </State>
    <State Name="GA">
        <Neighbours>
            <Neighbour>AL</Neighbour>
            <Neighbour>FL</Neighbour>
            <Neighbour>NC</Neighbour>
            <Neighbour>SC</Neighbour>
            <Neighbour>TN</Neighbour>
        </Neighbours>
    </State>
    ...
</ArrayOfState>

As an aside, is it also possible to have the contents of the "Neighbour" elements as attributes of those elements (i.e. <Neighbour name="XX"/>)?

Upvotes: 2

Views: 563

Answers (1)

remarkies
remarkies

Reputation: 123

[Serializable]
public class Worksheet
{
    [XmlRoot(ElementName = "XML")]
    public class XML
    {
        [XmlArray("States")]
        public List<State> States { get; set; }
    }

    public class State
    {
        [XmlAttribute]
        public string Name { get; set; }

        [XmlArray("Neighbours")]
        [XmlArrayItem("Neighbour")]
        public List<Neighbour> Neighbours { get; set; }
    }

    public class Neighbour
    {
        [XmlAttribute]
        public string Name { get; set; }
    }
}

public static void Main(string[] args)
{
    Worksheet.XML xml = PopulateListOfStates();

    XmlSerializer serializer = new XmlSerializer(typeof(Worksheet.XML));
    using (StreamWriter writer = new StreamWriter(@"C:\output.xml", false))
    {
        serializer.Serialize(writer, xml);
    }
}

Upvotes: 2

Related Questions