如何选择子节点而不是该子元素的整个子元素

时间:2012-12-14 05:30:04

标签: xml linq-to-xml

<categories>
<category text="Arts">
  <category>
        <category text="Design"/>
        <category text="Visual Arts"/>
   <category>
</category>
<category text="Business">
    <category>
        <category text="Business News"/>
        <category text="Careers"/>
        <category text="Investing"/>
   </category>
</category>
<category text="Comedy"/>
</categories>

目前我正在使用

xDoc.Descendants("category").Where(a => a.Attribute("text").Value == "Arts").Descendants("category")

上面的代码返回了包含属性&#34; Arts&#34;的所有类别元素。 我想要的只是类别下面的类别节点,属性为&#34; Arts&#34; 不是具有文本属性设计和视觉艺术的类别。我想要整个类别节点,如

 <category>
    <category text="Design"/>
    <category text="Visual Arts"/>
 <category>

1 个答案:

答案 0 :(得分:1)

你走了,希望你仍然需要这个:

    string category = "Business";
    var children = xDoc.Root.Elements("category").Where(a => a.Attribute("text").Value == category).Elements();