Microsofts System.Xml.XPath nuget-package,可用于.NET 4.6,声称支持XPath 1.0和2.0。 De documentation说descibes命名空间:在System.Xml.XPath中启用XPath2查询(XPathException:无效令牌)
System.Xml.XPath命名空间包含定义用于浏览和编辑XML信息项的游标模型的类作为XQuery 1.0和XPath 2.0数据模型的实例。
升级Visual Studio后,升级和我的所有项目到框架版本4.6我仍然无法获得最简单的XPath-2.0 for-expression工作。根据specification,他们应该工作。
我无法想象微软声称支持它实际上不支持的东西,所以显然我做错了什么。 如何正确使用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"
}
P.S. 其实我是想什么,是为了得到这样的工作:
[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);
}
}
“中的XQuery 1.0和XPath 2.0数据模型”是有关标准的参考 - 这并不意味着xpath 2导航被支持。我无法立即在文档中找到它只解释了xpath 1的位置。0支持;如果我能的话,我会把它放在一个答案 – AakashM