如何使用XPath用的XDocument?如何使用、XPath、XDocument

2023-09-02 01:35:14 作者:ソ芜夏、不言殇

还有一个类似的问题,但似乎该解决方案并没有在我的情况制定出:Weirdness用的XDocument,XPath和命名空间

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

下面是我有工作的XML:

Here is the XML I am working with:

<?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>

和下方则是code,我认为它应该工作,但事实并非如此......

And below is the code that I thought it should be working but it didn't...

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

有没有人有什么想法? 谢谢你。

Does anyone have any ideas? Thanks.

推荐答案

如果您的XDocument它更容易使用LINQ到XML:

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;

如果您确信XPath是你需要的唯一的解决办法:

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;