0

Here's the XML:

<xml id = "1234">
    <connect id="2"/>
    <connect id="1"/>
    <connect id="21"/>
    <connect id="3"/>
    <connect id="7"/>
</xml>

Currently I am doing this:

public class xml
{
    //Constructor

    [XmlAttribute ("id")]
    public uint id;

    [XmlElement ("connect")]
    public List<Connection> Connections { get; set; }

    //Deserializer
}

public class Connection
{
    [XmlAttribute ("id")]
    public uint id { get; set; }
}

The goal is to get rid of the Connection class entirely and Deserialize the xml straight into:

List<uint> connections;
0

1 Answer 1

1

First, your XML is not valid, i guess it's just a typo - there no end tag for "connect".

I recommend you to use linq XDocument.
Then it's easy:

XDocument xdoc = XDocument.Parse(xml);
List<uint> list = xdoc
                    .Descendants("connect")
                    .Select(node => uint.Parse(node.Attribute("id").Value))
                    .ToList();
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to achieve this using System.Xml.Serialization?
Thanks! This was exactly the solution I was looking for. I didn't realize the potential of XDocument.
<connect /> is self closing. why shouldn't it be valid then?
@da_berni, the question was edited and fixed after i've posted that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.