how to use XPath with XDocument?

后端 未结 3 1903
悲哀的现实
悲哀的现实 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 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;
    

提交回复
热议问题