Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I query an XDocument with a 'path'?

Tags:

I would like to query an XDocument object for a given path, (e.g. "/path/to/element/I/want") but I don't know how to proceed.

like image 865
binncheol Avatar asked Jun 27 '12 10:06

binncheol


2 Answers

You can use methods from System.Xml.XPath.Extensions to do this.

For example, if you want to select a single element, you would use XPathSelectElement():

var element = doc.XPathSelectElement("/path/to/element/I/want"); 

The queries don't have to be simple paths like what you described, they use the XPath language.

like image 144
svick Avatar answered Oct 09 '22 16:10

svick


Even though this is a somewhat older post, it should be noted that LINQ-to-XML can be used as an alternative to System.XML.XPath to find elements based on a path within an XDocument

Example:

var results = x.Elements("path").Elements("to").Elements("element").Elements("I").Elements("want").FirstOrDefault(); 

Note: The LINQ to XML command may need to be altered to accommodate for the actual structure and/or cardinality of the XML.

https://msdn.microsoft.com/en-us/library/bb675156.aspx

like image 30
Seymour Avatar answered Oct 09 '22 16:10

Seymour