Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq To XML - Using XDocument and creating list of objects

Tags:

c#

xml

linq

I have to read an XML document and insert the values into a List<T> of my objects.

Class (Result)

+Result
-username
-dob
-answer1
-answer2
-uuid

Below is the XML format structure

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<export exportDate="2012-11-07T12:03:52.823+11:00">
    <survey type="USER" completion="2012-11-07T11:46:52.754+11:00" reference="2012-11-07T11:30:34.680+11:00" year="2012" uuid="226f2aa3-46e6-46ab-8995-7d52eb21d5f4">
        <user xsi:type="USER" created="2012-11-07T11:09:30.409+11:00" dob="08/06/1988" surname="Billy" name="Bob" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
        <subject created="2012-11-07T11:09:30.409+11:00" dob="08/06/1988" surname="Billy" name="Bob"/>
        <version released="1970-01-01T10:00:02.012+10:00" version="1"/>
        <result group="2" rawscore="2.4" metric="1"/>
        <result group="2" rawscore="2.0" metric="2"/>
        <answer score="1" question="6"/>
        <answer score="2" question="7"/>
    </survey>       
</export>

My current progress

I was previously using XmlDocument as I have in the past but now that Im working with Linq im sure this can be done in just a few lines. I dont like the look of the code below, if anyway has some tips please help.

thankyou

    List<Result> results = new List<Result>();

    XmlDocument doc = new XmlDocument();
    doc.Load(filename); 

    XmlNodeList objects = doc.GetElementsByTagName("survey"); 
    foreach (XmlNode o in objects)
    {
        Result result = new Result();

        if (o.Attributes["type"].Value == "USER" || o.Attributes["type"].Value == "ADMIN")
        {
            result.surveycompleted = o.Attributes["completion"].Value;

            XmlNodeList usernodes = o.SelectNodes("user");
                ....
            if (usernodes.Count > 0)
            {}
            else
            { 
like image 518
IEnumerable Avatar asked Oct 22 '22 02:10

IEnumerable


1 Answers

Use LINQ2XML:

XElement doc=XElement.Load(filename);
List<Result> lstSurvey=doc.DescendantsAndSelf("Survey").Select(x=>
new Result
{
    uuid=x.Element("Survey").Attribute("uuid").Value,
    username=x.Element("user").Attribute("name").Value,
    dob=x.Element("user").Attribute("dob").Value,
    answer1=x.Elements("answer").First().Value,
    answer2=x.Elements("answer").Skip(1).First().Value
}
).ToList<Result>();
like image 130
Anirudha Avatar answered Oct 24 '22 18:10

Anirudha