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

28,279

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)
Share:
28,279
Mark Stewart
Author by

Mark Stewart

Updated on July 09, 2022

Comments

  • Mark Stewart
    Mark Stewart almost 2 years

    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!

  • Mark Stewart
    Mark Stewart over 14 years
    Indeed I did! Thanks very much.