Search code examples
c#xmllinqxpathxmlreader

Parsing XML file in C#


I have an XML File, generated by library written in c++:

<?xml version="1.0" encoding="UTF-8" ?>
<main>
    <days>
        <day>
            <date>27.06.2014</date>
            <p/>
        </day>
        <day>
            <date>28.06.2014</date>
            <p>
                <short>short value</short>
                <name>name value</name>
                <type>type value</type>
                <aud>aud value</aud>
                <tr>tr value</tr>
                <added>added value</added>
            </p>
            <p>
                <short>short value</short>
                <name>name value</name>
                <type>type value</type>
                <aud>aud value</aud>
                <tr>tr value</tr>
                <added>added value</added>
            </p>
        </day>
    ...
    </days>
    <di>
        <did>
            <dayname>Пн</dayname>
            <sw>1</sw>
            <st>8:00-9:35</st>
        </did>              
        <did>
            <dayname>Вт</dayname>
            <sw>2</sw>
            <st>9:45-11:20</st>
        </did>  
    ...
    </di>
</main>

I read these xml file like below:

XmlTextReader r = new XmlTextReader("out.xml");
while (r.Read())
{
    if (r.Name == "date") { r.Read(); dates[c1] = (r.Value); c1++; }
    else if (r.Name == "short") { r.Read(); shorts[c2] = (r.Value); c2++;  }
    else if (r.Name == "name") { r.Read(); names[c3] = (r.Value); c3++;  }
    else if (r.Name == "type") { r.Read(); types[c4] = (r.Value); c4++; }
    else if (r.Name == "aud") { r.Read(); auds[c5] = (r.Value); c5++; }
    else if (r.Name == "tr") { r.Read(); trs[c6] = (r.Value); c6++; }
    else if (r.Name == "sw") { r.Read(); ws[c7] = (r.Value); c7++; }
    else if (r.Name == "st") { r.Read(); st[c8] = (r.Value); c8++; }
}
r.Close();

How do I parse the file, so that I can understand what the parameter to which the day belongs, especially if there are several in one day ("p" in this case)? Trying to find a solution in the Internet, many people say it is better to use "LINQ to XML" or "XPath", but how to maintain object dependencies nobody says.


Solution

  • Load your xml using the XDocument class and then you can traverse it using the Descendants or Element methods.

    var xml = XDocument.Load("your xml string");
    foreach (var day in xml.Descendants("day"))
    {
        var pChildren = day.Descendants("p").ToList();
        var aretThereMorePs = pChildren.Count() > 1;
        foreach (var p in pChildren)
        {
            var shortVal = (string)p.Element("short");
            //etc
        }
    }