显示节点的不同值

时间:2017-05-23 13:53:49

标签: xml xquery

当我尝试输出不同的作者姓名和姓氏时,我的代码不会输出节点。

    distinct-values(
  for $b in doc("book.xml")//book/author
order by $b/name, $b/surname
return <author>{string($b/name), string($b/surname)}</author>
)

使用这个xml。

<?xml version="1.0" encoding="UTF-8"?> 
<bib>
    <book year="1994">
        <title>TCP/IP Illustrated</title>
        <author>
            <surname>Stevens</surname>
            <name>W.</name>
        </author>
        <editorial>Addison-Wesley</editorial>
        <price> 65.95</price>
    </book>

    <book year="1992">
        <title>Advan Programming for Unix environment</title>
        <author>
            <surname>Stevens</surname>
            <name>W.</name>
        </author>
        <editorial>Addison-Wesley</editorial>
        <price>65.95</price>
    </book>

     <book year="2000">
        <title>Millenium</title>
        <author>
            <surname>Falk</surname>
            <name>Lombardo</name>
        </author>
        <editorial>Morgan Kaufmann editorials</editorial>
        <price>19.50</price>
    </book>

    <book year="2000">
        <title>Data on the Web</title>
        <author>
            <surname>Abiteboul</surname>
            <name>Serge</name>
        </author>
        <author>
            <surname>Buneman</surname>
            <name>Peter</name>
        </author>
        <author>
            <surname>Suciu</surname>
            <name>Dan</name>
        </author>
        <editorial>Morgan Kaufmann editorials</editorial>
        <price>39.95</price>
    </book>


    <book year="1999">
        <title> Economics of Technology for Digital TV</title>
        <editor>
          <surname>Gerbarg</surname>
            <name>Darcy</name>
          <afiliacion>CITI</afiliacion>
        </editor>
        <editorial>Kluwer Academic editorials</editorial>
        <price>129.95</price>
    </book>
</bib>

以下代码输出:

Dan Suciu
Lombardo Falk
Peter Buneman
Serge Abiteboul
W. Stevens

但我想得到:

<author>Dan Suciu</author>
<author>Lombardo Falk</author>
<author>Peter Buneman</author>
<author>Serge Abiteboul</author>
<author>W. Stevens</author>

有人能告诉我我做错了什么吗?感谢。

1 个答案:

答案 0 :(得分:1)

问题是distinct-values()期望并返回一系列原子值,即你的<author/>元素首先被转换为字符串。

因此,您希望先获取不同的名称,然后再将其转换为元素。这样的东西应该返回预期的结果:

for $name in distinct-values(
  for $b in doc("book.xml")//book/author
  order by $b/name, $b/surname
  return string-join(($b/name, $b/surname), " ")
)
return <author>{ $name }</author>