使用 XQuery/XPath 获取元素父节点的属性值 [英] Using XQuery/XPath to get the attribute value of an element's parent node

查看:45
本文介绍了使用 XQuery/XPath 获取元素父节点的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这个 xml 文档:

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>

正在被这个 xquery 处理的:

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

我收到以下错误:

"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.

干杯!

推荐答案

您编写的查询正在选择属性 f.但是,从 XQuery 返回属性节点是不合法的.错误是指输出文档,这里只包含一个属性(虽然这个错误信息有误导性,因为从技术上讲,这里没有输出文档,只返回了一个属性节点).

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)

这篇关于使用 XQuery/XPath 获取元素父节点的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆