如何遍历父元素及其子元素并打印元素名称 xquery
How to iterate through parent element and its child elements and print element name xquery
我想遍历所有父元素和子元素并打印出元素名称。
例如
<Asdf>
<parentnode1>
<childnode1>...</childnode1>
<childnode2>...</childnode2>
</parentnode1>
<parentnode2>
<childnode3>..</childnode3>
<childnode4>..</childnode4>
</parentnode2>
</Asdf>
解决方案是:
parentnode1 childnode1 childnode2 parentnode2 childnode3 childnode4
现在我得到了什么:
let $a := fn:doc('asdf.xml')/Asdf/*
return
for $z in $a
return $z/name()
for $x in $a/*
return $x/name()
我错过了什么,为什么这个嵌套的 for 循环不起作用?
只需使用这个 XQuery:
let $xdoc := doc('asdf.xml')/Asdf//*
return $xdoc/name()
输出是字符串
parentnode1 childnode1 childnode2 parentnode2 childnode3 childnode4
以上 XQuery 遍历从 /Asdf
开始的所有子元素。
您的代码无法运行的原因是语法错误。在 FLWOR 语句的 return
中,您有两个想要 return 的序列。
因此,您需要将其括在括号中并添加一个逗号,我认为您希望在 for 循环中引用 $z
而不是 $a
:
let $a := fn:doc('asdf.xml')/Asdf/*
return
for $z in $a
return ($z/name(),
for $x in $z/*
return $x/name()
)
或更短的版本:
for $z in $a
return ($z/name(), $z/*/name())
@zx485 提供了一种更简单的方法来实现您想要的。更简单和更短的是:
doc('asdf.xml')/Asdf//*/name()
我想遍历所有父元素和子元素并打印出元素名称。
例如
<Asdf>
<parentnode1>
<childnode1>...</childnode1>
<childnode2>...</childnode2>
</parentnode1>
<parentnode2>
<childnode3>..</childnode3>
<childnode4>..</childnode4>
</parentnode2>
</Asdf>
解决方案是:
parentnode1 childnode1 childnode2 parentnode2 childnode3 childnode4
现在我得到了什么:
let $a := fn:doc('asdf.xml')/Asdf/*
return
for $z in $a
return $z/name()
for $x in $a/*
return $x/name()
我错过了什么,为什么这个嵌套的 for 循环不起作用?
只需使用这个 XQuery:
let $xdoc := doc('asdf.xml')/Asdf//*
return $xdoc/name()
输出是字符串
parentnode1 childnode1 childnode2 parentnode2 childnode3 childnode4
以上 XQuery 遍历从 /Asdf
开始的所有子元素。
您的代码无法运行的原因是语法错误。在 FLWOR 语句的 return
中,您有两个想要 return 的序列。
因此,您需要将其括在括号中并添加一个逗号,我认为您希望在 for 循环中引用 $z
而不是 $a
:
let $a := fn:doc('asdf.xml')/Asdf/*
return
for $z in $a
return ($z/name(),
for $x in $z/*
return $x/name()
)
或更短的版本:
for $z in $a
return ($z/name(), $z/*/name())
@zx485 提供了一种更简单的方法来实现您想要的。更简单和更短的是:
doc('asdf.xml')/Asdf//*/name()