如何遍历父元素及其子元素以及打印元素名称xquery

问题描述 投票:1回答:2

我想遍历所有父元素和子元素并打印出元素名称。

例如

<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循环不起作用?

xml xsd xquery
2个回答
2
投票

仅使用此XQuery:

let $xdoc := doc('asdf.xml')/Asdf//*
return $xdoc/name()

输出是字符串

[parentnode1 childnode1 childnode2 parentnode2 childnode3 childnode4

上面的XQuery迭代从/Asdf开始的所有子元素。


1
投票

您的代码无法正常工作的原因是您遇到语法错误。在FLWOR语句的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()
© www.soinside.com 2019 - 2024. All rights reserved.