Joe Tyman
Joe Tyman

Reputation: 1417

How to find an Element, not knowing how deep it is nested using Linq to XML?

I have XML document that is like this:

<BrowseNodes>
<BrowseNode>
  <BrowseNodeId>4075981</BrowseNodeId>
  <Name>Nutrition Bars</Name>
  <Ancestors>
  <BrowseNode>
     <BrowseNodeId>4075971</BrowseNodeId>
     <Name>Nutrition Bars &amp; Drinks</Name>
        <Ancestors>
        <BrowseNode>
            <BrowseNodeId>3764441</BrowseNodeId>
            <Name>Diet &amp; Nutrition</Name>
            <Ancestors>
            <BrowseNode>
                <BrowseNodeId>3760931</BrowseNodeId>
                <Name>Products</Name>
                <IsCategoryRoot>1</IsCategoryRoot>
                <Ancestors>
                <BrowseNode>
                   <BrowseNodeId>3760901</BrowseNodeId>
                   <Name>Health &amp; Personal Care</Name>
                </BrowseNode>
                </Ancestors>
             </BrowseNode>
             </Ancestors>
          </BrowseNode>
          </Ancestors>
       </BrowseNode>
      </Ancestors>
 </BrowseNode>
</BrowseNodes>

I want to XLINQ query to find the Category root. How do that with out nothing how many ancestor may actually be included?

Upvotes: 1

Views: 188

Answers (1)

DaveShaw
DaveShaw

Reputation: 52788

You should use the Descendants property.

var node = 
  XElement.Parse(xmlString)
  .Descendants()
  .Where(xe => xe.Element("IsCategoryRoot") != null && xe.Element("IsCategoryRoot").Value == "1");

Upvotes: 4

Related Questions