Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query an XDocument for elements by name at any depth

I have an XDocument object. I want to query for elements with a particular name at any depth using LINQ.

When I use Descendants("element_name"), I only get elements that are direct children of the current level. I'm looking for the equivalent of "//element_name" in XPath...should I just use XPath, or is there a way to do it using LINQ methods?

like image 824
Rich Avatar asked Feb 19 '09 16:02

Rich


People also ask

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .

What is XDocument C#?

The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.

What is an XElement?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.

What is LINQ to XML?

LINQ to XML is an XML programming interface. LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.


1 Answers

Descendants should work absolutely fine. Here's an example:

using System; using System.Xml.Linq;  class Test {     static void Main()     {         string xml = @" <root>   <child id='1'/>   <child id='2'>     <grandchild id='3' />     <grandchild id='4' />   </child> </root>";         XDocument doc = XDocument.Parse(xml);          foreach (XElement element in doc.Descendants("grandchild"))         {             Console.WriteLine(element);         }     } } 

Results:

<grandchild id="3" />
<grandchild id="4" />

like image 87
Jon Skeet Avatar answered Sep 20 '22 15:09

Jon Skeet