mappo
mappo

Reputation: 476

Difference between XPath & XQuery when selecting attribute value

There seems to be a difference in how XPath and XQuery selects attributes. Here is a toy example stolen from W3Schools:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="children">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
</bookstore> 

I want to retrieve the values of the lang attributes. So, naively I do: //title/@lang which works perfectly ... on an XPath evaluator but not on an XQuery evaluator.

What I need to know: How should I write my XPath expression to work on an XQuery evaluator?

What I want to know: What is going on?!

Here's the TL part:

I'm on a legacy platform without these capabilities so I send the XML and my query expression to an external service, which I believe is a Saxon-based XQuery evaluator. My syntax works as expected on CodeBeautify's XPath Tester.

I've also verified this difference on xpathtester.com: It works as expected in XPath mode but not in XQuery mode. (Note: link is not encrypted.).

xpathtester.com returns the following error message: ERROR - Cannot create an attribute node (lang) whose parent is a document node

Upvotes: 1

Views: 251

Answers (2)

mappo
mappo

Reputation: 476

After really having understood what @Martin Honnen and @Aaron were talking about and some deep dives in tutorials, I think I've come up with a solution that I'm happy with:

string-join((for $l in //title/@lang return string($l)) , ',')

https://xqueryfiddle.liberty-development.net/3Nzd8bR/2

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163458

The expression //title/@lang is valid under both XPath and XQuery, and returns a sequence of two attribute nodes.

Where you are seeing differences is in how different XPath and XQuery clients handle a result consisting of two attribute nodes.

If the tool tries to serialize the result as XML, it's going to fail, because XML serialization tries to construct a document node and attach the attributes to the document.

So you need to look at what options your XPath or XQuery tool provides for displaying the results.

Upvotes: 1

Related Questions