how to use XPath with XDocument ?

how to use XPath with XDocument ?

Asked on December 28, 2018 in XML.
Add Comment


  • 2 Answer(s)

    Use XPath with XDocument:

         It is easier to use LINQ-to-XML if user have XDocument.

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

         If XPath is the only answer then,

    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;
    
    Answered on December 28, 2018.
    Add Comment

    MS implements XPath 1.0, so try the below code:

    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);
    
    Answered on December 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.