如何从xquery正确生成xml

时间:2013-02-06 14:56:29

标签: xquery

我是xquery的新手,正在尝试阅读有关使用该工具的不同参考资料。我一直试图玩测试并尝试生成一些xml格式的消息,但这个让我困惑。这是我的xQuery代码:

示例XQuery

declare variable $requestBody as element() external;
declare function VerifyOrderDetailTransformation($requestBody as element())
as element() {
    <msg>
        <header>
            <headtitle>This is the title</headtitle>
        </header>
        <dbody>
            {GenerateEquipmentListNodes($requestBody)} 
        </dbody>
    </msg>
};

declare function GenerateEquipmentListNodes($requestBody as element())
as element()* {

    let $titleList := (
        for $e in $requestBody//bookstore//book
            let $dTitle := $e/title/text()
            return 
               <theTitle>{$dTitle}</theTitle>
        )

    return 
       <dTitleList>
           {$titleList}
       </dTitleList>
};

VerifyOrderDetailTransformation($requestBody)

示例XML

<bookstore>

<book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
</book>

<book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
</book>

<book category="WEB">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
</book>

<book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
</book>

</bookstore>

这是通过在XML上运行xQuery生成的输出:

当前输出

<msg> 
    <head> 
        <title>This is the title</title> 
    </head> 
    <body> 
        <dTitleList/> 
    </body> 
</msg>

预期输出

<msg> 
    <head> 
        <title>This is the title</title> 
    </head> 
    <body> 
        <dTitleList> 
        <theTitle>Everyday Italian</theTitle>
        <theTitle>Harry Potter</theTitle>
        <theTitle>XQuery Kick Start</theTitle>
        <theTitle>Learning XML</theTitle>
        <dTitleList/> 
    </body> 
</msg>

我的问题是,我可能错过了什么?

1 个答案:

答案 0 :(得分:1)

您的输入存在一些问题:您正在查询此XML:

<bookstore>
  <book>
    <!-- snip -->
  </book>
  <!-- snip -->
</bookstore>

XPath查询的第一部分,即$queryBody//bookstore,查找下面有元素<bookstore/>的所有后代元素 - 返回空结果的内容。 $queryBody//bookstore也不会这样做,因为上下文已经在<bookstore/>元素上。

出于这个原因,请忽略//bookstore,因此您应该$queryBody//book

将此函数与更改后的XPath一起使用:

declare function local:GenerateEquipmentListNodes($requestBody as element())
as element()* {

    let $titleList := (
        for $e in $requestBody//book
            let $dTitle := $e/title/text()
            return 
               <theTitle>{$dTitle}</theTitle>
        )

    return 
       <dTitleList>
           {$titleList}
       </dTitleList>
};

还有一句话:您应该将自己的函数放入local:函数命名空间或定义自己的函数。不鼓励使用默认命名空间,并且与所有处理器不兼容。我将其更改为local: - 命名空间。