Microsoft 的 System.Xml.XPath nuget-package 可用于 .NET 4.6,声称支持 XPath 1.0 和 2.0。德文档 https://msdn.microsoft.com/en-us/library/system.xml.xpath(v=vs.110).aspx说描述了命名空间:
System.Xml.XPath 命名空间包含的类定义了用于导航和编辑 XML 信息项的游标模型,作为 XQuery 1.0 和 XPath 2.0 数据模型的实例。
升级 Visual Studio、将我的所有项目升级到框架版本 4.6 后,我仍然无法让最简单的 XPath-2.0 for 表达式工作。根据规格 https://www.w3.org/TR/xpath20/#id-for-expressions,他们应该工作。
我无法想象微软声称支持它实际上并不支持的东西,所以显然我做错了。如何正确使用 XPath2 查询?
[TestMethod]
public void TestXPath2()
{
// The System.Xml.XPath namespace contains the classes that define a cursor model for navigating and editing XML information items as instances of the
// XQuery 1.0 and XPath 2.0 Data Model.
var expression = "for $x in /Root/Foo/Bar return $x";
var compiledExpression = System.Xml.XPath.XPathExpression.Compile(expression);
// throws XPathException: "for ... has an invalid token"
}
附:
我真正想要的是让这样的事情发挥作用:
[TestMethod]
public void TestLibraryForCustomer1()
{
string xmlFromMessage = @"<Library>
<Writer ID=""writer1""><Name>Shakespeare</Name></Writer>
<Writer ID=""writer2""><Name>Tolkien</Name></Writer>
<Book><WriterRef REFID=""writer1"" /><Title>King Lear</Title></Book>
<Book><WriterRef REFID=""writer2"" /><Title>The Hobbit</Title></Book>
<Book><WriterRef REFID=""writer2"" /><Title>Lord of the Rings</Title></Book>
</Library>";
var titleXPathFromConfigurationFile = "./Title";
var writerXPathFromConfigurationFile = "for $curr in . return /Library/Writer[@ID=$curr/WriterRef/@REFID]/Name";
var library = ExtractBooks(xmlFromMessage, titleXPathFromConfigurationFile, writerXPathFromConfigurationFile).ToDictionary(b => b.Key, b => b.Value);
Assert.AreEqual("Shakespeare", library["King Lear"]);
Assert.AreEqual("Tolkien", library["The Hobbit"]);
Assert.AreEqual("Tolkien", library["Lord of the Rings"]);
}
[TestMethod]
public void TestLibraryForCustomer2()
{
string xmlFromMessage = @"<Library>
<Writer ID=""writer1"">
<Name>Shakespeare</Name>
<Book><Title>Sonnet 18</Title></Book>
</Writer>
<Writer ID=""writer2"">
<Name>Tolkien</Name>
<Book><Title>The Hobbit</Title></Book>
<Book><Title>Lord of the Rings</Title></Book>
</Writer>
</Library>";
var titleXPathFromConfigurationFile = "./Title";
var writerXPathFromConfigurationFile = "../Name";
var library = ExtractBooks(xmlFromMessage, titleXPathFromConfigurationFile, writerXPathFromConfigurationFile).ToDictionary(b => b.Key, b => b.Value);
Assert.AreEqual("Shakespeare", library["Sonnet 18"]);
Assert.AreEqual("Tolkien", library["The Hobbit"]);
Assert.AreEqual("Tolkien", library["Lord of the Rings"]);
}
public IEnumerable<KeyValuePair<string,string>> ExtractBooks(string xml, string titleXPath, string writerXPath)
{
var library = XDocument.Parse(xml);
foreach(var book in library.Descendants().Where(d => d.Name == "Book"))
{
var title = book.XPathSelectElement(titleXPath).Value;
var writer = book.XPathSelectElement(writerXPath).Value;
yield return new KeyValuePair<string, string>(title, writer);
}
}