how to use XPath with XDocument? how to use XPath with XDocument? xml xml

how to use XPath with XDocument?


If you have XDocument it is easier to use LINQ-to-XML:

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

If you are sure that XPath is the only solution you need:

using System.Xml.XPath;var document = XDocument.Load(fileName);var namespaceManager = new XmlNamespaceManager(new NameTable());namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;


XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);


you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;using System.Xml.XPath;var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it