XDocument and XPath

To use XDocument with XPath, you will need to reference the following namespace.

 

  • using System.Xml
  • using System.Xml.XPath

 

The former is useful to introduce XDocument, the later will add the Extension method to make it work well with the XPath. One of the method that we will introduce in this example is the 

 

public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression);
 

Below shows how you query against the following data.

 

<?xml version="1.0" encoding="utf-8"?>
<Report Id="ID1" Type="Demo Report" Created="2011-01-01T01:01:01+11:00" Culture="en" xmlns="http://demo.com/2011/demo-schema">
    <ReportInfo>
        <Name>Demo Report</Name>
        <CreatedBy>Unit Test</CreatedBy>
    </ReportInfo>
</Report>

 

var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
 

 

You can also do with this (with help from XPath)

var document = XDocument.Load("fileName"); // Added missing endquote. It won't submit unless I type more.
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("emtpy", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/emtpy:Report/emtpy:ReportInfo/emtpy:Name", namespaceManager).Value;
 

 

 

 

 

 

你可能感兴趣的:(XDocument XPath)