how to use XPath with XDocument?

后端 未结 3 1889
悲哀的现实
悲哀的现实 2020-11-27 03:39

There is a similar question, but it seems that the solution didn\'t work out in my case: Weirdness with XDocument, XPath and namespaces

Here is the XML I am working

相关标签:
3条回答
  • 2020-11-27 03:59

    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);
    
    0 讨论(0)
  • 2020-11-27 04:05

    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

    0 讨论(0)
  • 2020-11-27 04:10

    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;
    
    0 讨论(0)
提交回复
热议问题