用c#解析XML文件

本文关键字:文件 XML 解析 | 更新日期: 2023-09-27 18:10:30

我有一个XML文件,由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>

我读这些xml文件如下:

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();

我如何解析文件,以便我能够理解日期所属的参数,特别是如果一天中有几个参数(在这种情况下为"p")?试图在互联网上找到一个解决方案,许多人说最好使用"LINQ to XML"或"XPath",但如何维护对象依赖没有人说。

用c#解析XML文件

使用XDocument类加载xml,然后可以使用Descendants或Element方法遍历它。

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
    }
}