Jacob S Jacob S - 2 months ago 10
C# Question

Format XML containing List for Deserialization

I have some data which I need to bring from an XML file to a PostgreSQL database through a C# application I am currently working on.

The problem I face now is that I need to add some kind of list to the XML now. Currently it looks something like this:

<itemOne>stuff</itemOne>
<itemTwo>otherStuff</itemTwo>
<listOfItems>
<listItem>
<partOne>123</partOne>
<partTwo>abc</partTwo>
</listItem>
<listItem>
<partOne>123</partOne>
<partTwo>abc</partTwo>
</listItem>
</listOfItems>


So I found quite some threads which handle the topic of how to deserialize lists. But all of them start by saying that the proposed XML should be modified. As I have all the freedom that I could wish for in that regard, I'd like to first create an optimal XML format at first.

Well, and afterwards deserialize it. So if there is any format for lists which is automatically processed by XmlSerializer.Deserialize() it would be amazing.

Answer

That data will already be processed automatically by XmlSerializer, as long as the class is shaped to match. For example:

[XmlRoot("yourRootName")]
public class Foo {
    [XmlElement("itemOne")] public string A {get;set;}
    [XmlElement("itemTwo")] public string B {get;set;}

    [XmlArray("listOfItems")]
    [XmlArrayItem("listItem")]
    public List<Bar> Bars {get;set;}
}
public class Bar {
    [XmlElement("partOne")] public int C {get;set;}
    [XmlElement("partTwo")] public string D {get;set;}
}

Of course, if it was me I'd be tempted to be terse, with:

<betterName foo="stuff" blab="otherStuff">
     <nameMe a="123" b="abc"/>
     <nameMe a="456" b="def"/>
</betterName>

which just requires some minimal changes:

[XmlRoot("betterName")]
public class Foo {
    [XmlAttribute("foo")] public string A {get;set;}
    [XmlAttribute("bar")] public string B {get;set;}

    [XmlElement("nameMe")]
    public List<Bar> Bars {get;set;}
}
public class Bar {
    [XmlAttribute("a")] public int C {get;set;}
    [XmlAttribute("b")] public string D {get;set;}
}
Comments