Extract an XML element from an XML file using XPath

I have the following XML document:

<MimeType> <Extension>.aab</Extension> <Value>application/x-authorware-</Value> </MimeType> <MimeType> <Extension>.aam</Extension> <Value>application/x-authorware-</Value> </MimeType> 

The entire document contains about 700 entries. How can I extract a single MimeType element using XPath and populate it into a strongly typed C # MimeType ?

+7
c # xml xpath
source share
4 answers

Use XmlDocument.SelectSingleNode .

Example:

 XmlDocument doc = new XmlDocument(); doc.Load("yourXmlFileName"); XmlNode node = doc.SelectSingleNode("yourXpath"); 

Then you can access node.ChildNodes to get the values ​​you need (example):

 string extension = node.ChildNodes[0].InnerText; string value = node.ChildNodes[1].InnerText; 

And then use these values ​​when constructing the MimeType object.

Edit: some information about XPath.
There are some really good XPath tutorials, try here and here . The W3C recommendation can be a bit overwhelming.
As an example, you can try the following XPath to select the first MimeType node in the document (where root is the name of your root element):

 string xPath = "root/MimeType[1]" 

Hope this helps!

+13
source share

The following method should provide a structure for getting a MIME type here

 public MimeType RunXPath(string mimeType) { XmlNode node = _xmlDoc.SelectSingleNode( string.Format("//MimeType/Extension[text()="{0}"]/ancestor::MimeType", mimeType)); foreach(XmlNode node in nodes) { // Extract the relevant nodes and populate the Mime Type here... } return ... } 

The trick is to find the text-based MimeType in the extension, and then get the MimeType ancestor for that match.

+2
source share

You are using classes in the System.Xml.XPath namespace.

Tutorials from MSDN

+1
source share

Following @MiffTheFox answer you can use XPath with LINQ to XML . Here is an example based on your sample data.

1) First, the namespaces you will need:

 using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; 

2) Load the XML document in XElement :

 XElement rootElement = XElement.Parse(xml); 

3) Determine the XPath location path:

 // For example, to locate the 'MimeType' element whose 'Extension' // child element has the value '.aam': // // ./MimeType[Extension='.aam'] string extension = ".aam"; string locationPath = String.Format("./MimeType[Extension='{0}']", extension); 

4) Move the path to XPathSelectElement() to select the element of interest:

 XElement selectedElement = rootElement.XPathSelectElement(locationPath); 

5) Finally, retrieve the MimeType value associated with the extension:

 var mimeType = (string)selectedElement.Element("Value"); 
+1
source share

All Articles