在System.Xml.XPath中启用XPath2查询(XPathException:invalid token)

时间:2017-10-18 08:28:51

标签: c# .net xml xpath xpath-2.0

Microsofts System.Xml.XPath nuget-package,可用于.NET 4.6,声称支持XPath 1.0和2.0。 De documentation表示命名空间:

System.Xml.XPath命名空间包含定义游标模型的类,用于导航和编辑XML信息项,作为XQuery 1.0和XPath 2.0数据模型的实例。

升级Visual Studio,将我的所有项目升级到框架版本4.6后,我仍然无法使最简单的XPath-2.0 for-expression工作。根据{{​​3}},他们应该工作。

我无法想象微软会声称支持它实际上没有支持的东西,所以显然我做错了什么。 如何正确使用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);
        }
    }

2 个答案:

答案 0 :(得分:4)

Tomalek正确地指出:

  • .NET(在System.Xml.XPath中)不支持XPath 2.0,期间
  • 数据模型和查询语言是分开的。

所以我通过使用第三方XPath 2库XPath2 nuget package来解决它。这允许像

这样的表达式
for $c in . return ../Writer[@ID=$c/WriterRef/@REFID]/Name

请注意,我需要使用从书到作家的相对路径。这样做工作:

# does not work due to the absolute path
for $c in . return /Library/Writer[@ID=$c/WriterRef/@REFID]/Name

供将来参考:此代码在安装nuget pacage之后有效:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Wmhelp.XPath2;

namespace My.Library
{
    [TestClass]
    public class WmhelpTests
    {
        [TestMethod]
        public void LibraryTest()
        {
            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 ../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.XPath2SelectElement(titleXPath).Value;
                var writer = book.XPath2SelectElement(writerXPath).Value;
                yield return new KeyValuePair<string, string>(title, writer);
            }
        }
    }
}

答案 1 :(得分:1)

我怀疑XPath 2.0查询语言是否真的受到支持。

但是对于像你的要求那样简单的东西,XPath 1.0单线程就足够了。

string xml = @"<Root>
    <Foo ID=""foo1"">One</Foo>
    <Foo ID=""foo2"">Two</Foo>
    <Bar><FooRef REFID=""foo2"" /></Bar>
    </Root>";
var doc = XDocument.Parse(xml);
var matchingFoo = doc.XPathSelectElement("/Root/Foo[@ID = //Bar/FooRef/@REFID]");

Assert.AreEqual("Two", matchingFoo.value);

对于超出XPath 1.0功能的查询,请尝试使用LINQ。

在您的扩展示例中,您要做的是将书籍与作者联系起来。这很容易在LINQ连接中完成,如下所示:

var 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 libraryDoc = XDocument.Parse(xmlFromMessage);

var library = from title in libraryDoc.Descendants("Title")
    join writer in libraryDoc.Descendants("Writer")
    on title.Parent.Element("WriterRef").Attribute("REFID").Value equals writer.Attribute("ID").Value
    select new KeyValuePair<string, string>(title.Value, writer.Value);

现在libraryIEnumerable<KeyValuePair<string,string>>,其标题/作者配对。