C# 使用LINQ to XML解析深度嵌套的属性时出现问题

C# 使用LINQ to XML解析深度嵌套的属性时出现问题,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我一直在尝试用c解析这个xml <schema uri=http://blah.com/schema > <itemGroups> <itemGroup description="itemGroup1 label="itemGroup1"> <items> <item description="The best" itemId="1" label="Nutella"/> &l

我一直在尝试用c解析这个xml

<schema uri=http://blah.com/schema >
   <itemGroups>
     <itemGroup description="itemGroup1 label="itemGroup1">
       <items>
        <item description="The best" itemId="1" label="Nutella"/>
        <item description="The worst" itemId="2" label="Vegemite"/>
       </items>
     </itemGroup>
   </itemGroups>
</schema>

\itemGroup1\Nutella-The best
\itemGroup1\Vegemite-The worst
任何帮助或指导都将不胜感激

XDocument xDoc = XDocument.Load(myXml); //load your XML from file or stream

var rows = xDoc.Descendants("item").Select(x => string.Format(
                    @"\{0}-{1}\{2}-{3}",
                    x.Ancestors("itemGroup").First().Attribute("description").Value,
                    x.Ancestors("itemGroup").First().Attribute("label").Value,
                    x.Attribute("label").Value,
                    x.Attribute("description").Value));
让我们来分析一下我们正在做的事情:

degenantsitem获取整个文档中的所有元素

Selectx=>string.Formatformat,args将上一次操作中获得的每个参数投影到lambda中指定的任何格式。在这种情况下,一个

就XML树而言,我们处于同一级别,因此我们需要回滚该树以使用祖先获取父组的数据。因为该方法返回一系列元素,所以我们知道我们希望第一个元素离我们最近,这样我们就可以读取它的属性

现在,您有了一个IEnumerable,XML文档中的每个IEnumerable和指定格式的信息:

foreach(string row in rows)
{
    Console.WriteLine(row);
}

谢谢!由于以前从未解析过xml,您的解释帮助很大。干杯