如何在 XDocument 中使用 XPath?

还有一个类似的问题,但似乎没有解决我的情况: XDocument、 XPath 和名称空间的怪异之处

下面是我正在使用的 XML:

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

下面是代码,我认为它应该工作,但它没有..。

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);

有人有主意吗? 谢谢。

123547 次浏览

如果使用 XDocument,使用 LINQ-to-XML 会更容易:

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

如果确定 XPath 是您需要的唯一解决方案:

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;

MS 实现的 XPath 1.0没有默认名称空间的概念:

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);

你可以使用来自 微软的例子-对于你来说没有名称空间:

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

should do it

为了使用 w/o 默认名称空间后缀,我自动展开路径。

用法: SelectElement(xdoc.Root, "/Report/ReportInfo/Name");

private static XElement SelectElement(XElement startElement, string xpathExpression, XmlNamespaceManager namespaceManager = null) {
// XPath 1.0 does not have support for default namespace, so we have to expand our path.
if (namespaceManager == null) {
var reader = startElement.CreateReader();
namespaceManager = new XmlNamespaceManager(reader.NameTable);
}
var defaultNamespace = startElement.GetDefaultNamespace();
var defaultPrefix = namespaceManager.LookupPrefix(defaultNamespace.NamespaceName);
if (string.IsNullOrEmpty(defaultPrefix)) {
defaultPrefix = "ᆞ";
namespaceManager.AddNamespace(defaultPrefix, defaultNamespace.NamespaceName);
}
xpathExpression = AddPrefix(xpathExpression, defaultPrefix);
var selected = startElement.XPathSelectElement(xpathExpression, namespaceManager);
return selected;
}


private static string AddPrefix(string xpathExpression, string prefix) {
// Implementation notes:
// * not perfect, but it works for our use case.
// * supports: "Name~~" "~~/Name~~" "~~@Name~~" "~~[Name~~" "~~[@Name~~"
// * does not work in complex expressions like //*[local-name()="HelloWorldResult" and namespace-uri()='http://tempuri.org/']/text()
// * does not exclude strings like 'string' or function like func()
var s = Regex.Replace(xpathExpression, @"(?<a>/|\[@|@|\[|^)(?<name>\w(\w|[-])*)", "${a}${prefix}:${name}".Replace("${prefix}", prefix));
return s;
}

如果有人有更好的解决方案来查找元素和属性名称,请随意更改这篇文章。