Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XQuery/XPath to get the attribute value of an element's parent node

Tags:

Given this xml document:

<?xml version="1.0" encoding="UTF-8"?>
    <mydoc>
        <foo f="fooattr">
            <bar r="barattr1">
                <baz z="bazattr1">this is the first baz</baz>
            </bar>
            <bar r="barattr2">
                <baz z="bazattr2">this is the second baz</baz>
            </bar>
        </foo>
    </mydoc>

that is being processed by this xquery:

let $d := doc('file:///Users/mark/foo.xml')
let $barnode := $d/mydoc/foo/bar/baz[contains(@z, '2')]
let $foonode := $barnode/../../@f
return $foonode

I get the following error:

"Cannot create an attribute node (f) whose parent is a document node". 

It seems that the ../ operation is sort of removing the matching nodes from the rest of the document such that it thinks it's the document node.

I'm open to other approaches but the selection of the parent depends on the child attribute containing a certain sub-string.

Cheers!

like image 415
Mark Stewart Avatar asked Jan 29 '10 23:01

Mark Stewart


People also ask

Does XQuery use XPath?

XQuery is XPath compliant. It uses XPath expressions to restrict the search results on XML collections. For more details on how to use XPath, see our XPath Tutorial.

What is parent node in XPath?

In XPath, the parent node of the current node selected in the web page is retrieved using the Parent method. It comes in handy when we choose an element and need to utilise Xpath to fetch the parent element. This method can also be used to find out who the parent's parents are and abbreviated as (..).

What is XQuery and XPath?

XPath (XML path language) and XQuery (XML query language) are query languages defined by the W3C (World Wide Web Consortium) for querying XML documents. XPath is a language based on path expressions that allows the selection of parts of a given XML document.


1 Answers

The query you have written is selecting the attribute f. However it is not legal to return an attribute node from an XQuery. The error is refering to the output document which here contains just an attribute (although this error message is misleading, as technically there is no output document here, there is just an attribute node that is returned).

You probably wanted to return the value of the attribute rather than the attribute itself

return data($foonode)
like image 81
Oliver Hallam Avatar answered Oct 16 '22 17:10

Oliver Hallam