使用LINQ to XML解析深层嵌套属性时遇到问题

时间:2010-09-11 21:35:02

标签: 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"/>
        <item description="The worst" itemId="2" label="Vegemite"/>
       </items>
     </itemGroup>
   </itemGroups>
</schema>

\itemGroup1\Nutella-The best
\itemGroup1\Vegemite-The worst

任何帮助或指示都将不胜感激。

1 个答案:

答案 0 :(得分:6)

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

让我们分解我们正在做的事情:

  • xDoc.Descendants("item")获取整个文档中的所有<item>元素

  • Select(x => string.Format(format, args) 项目我们从上一次操作获得的每个<item>到我们在lambda中指定的格式。在这种情况下,formatted string

  • 就XML树而言,我们“处于”<item>级别,因此我们需要回滚树以使用{{1}获取父组的数据}。由于该方法返回一系列元素,我们知道我们想要第一个(离我们最近)所以我们可以读取它的属性。

现在,您有一个Ancestors,XML文档中每个IEnumerable<string>一个,以及您指定格式的信息:

<item>
相关问题