C#使用重复的节点模式解析XML

时间:2017-03-30 08:55:38

标签: c# xml linq

您好我有以下xml文件:

<?xml version="1.0" encoding="utf-8"?>
<Resources>
    <Category Cause="ONE">
        <Resource Component="AAA" Name="cBackgroundTextA" />
        <Resource Component="BBB" Name="cBackgroundTextB" />
        <Resource Component="CCC" Name="cBackgroundTextC" />
    </Category>
    <Category Cause="TWO">
        <Resource Component="DDD" Name="cBackgroundTextD" />
        <Resource Component="EEE" Name="cBackgroundTextE" />
        <Resource Component="FFF" Name="cBackgroundTextF" />
    </Category>
    <Category Cause="THREE">
        <Resource Component="GGG" Name="cBackgroundTextG" />
        <Resource Component="HHH" Name="cBackgroundTextH" />
        <Resource Component="III" Name="cBackgroundTextI" />
    </Category>
</Resources>

我如何得到以下内容:

  

ONE,AAA,cBackgroundTextA

     

ONE,BBB,cBackgroundTextB

     

ONE,CCC,cBackgroundTextC

     

TWO,DDD,cBackgroundTextD

     

TWO,EEE,cBackgroundTextE

     

...

3 个答案:

答案 0 :(得分:0)

尝试一下这一行:

XElement root;

foreach(var folder in root.Children()) { //For each folder
    var folderType = folder.Attribute("type").Value;
    foreach(var file in folder.Children()) { //For each  file

        Console.WriteLine($"{folderType} AND {file}");
    }
}

答案 1 :(得分:0)

我终于通过以下方式获得了价值:

xmlDocument = new XDocument();
xmlDocument = XDocument.Load(filePath, LoadOptions.None);

var categoryNodeList = XmlDocument.Descendants("Category");

    foreach (XElement categoryItem in categoryNodeList)
    {
        foreach (XElement resourceItem in categoryItem.Elements())
        {
            var XmlObject = new ResultDetail
            {
                Cause = categoryItem.Attribute("Cause").Value,
                Component = resourceItem.Attribute("Component").Value,
                Name = resourceItem.Attribute("Name").Value
            };
        }
    }

答案 2 :(得分:0)

可以使用单个LINQ查询收集所有必需的信息:

var query = from cat in XmlDocument.Descendants("Category");
            from res in cat.Elements()
            select new ResultDetail
                    {
                        Cause = cat.Attribute("Cause").Value,
                        Component = res.Attribute("Component").Value,
                        Name = res.Attribute("Name").Value
                    };