2

我正在尝试在此处使用 WikiBooks 中的“将 XML 转换为 JSON”示例https://en.wikibooks.org/wiki/XQuery/Convert_XML_to_JSON

xquery version "3.0";

declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method "json";
declare option output:media-type "application/json";

let $test := <root>
  <!-- simple elements -->
  <aaa>AAA</aaa>
  <bbb>BBB</bbb>
  <ccc>CCC</ccc>
  <!-- complex (nested) element -->
  <ddd>
     <eee>
        <fff>
           <ggg>GGG</ggg>
        </fff>
     </eee>
  </ddd>
  <!-- duplicate elements -->
  <hhh>HHH1</hhh>
  <hhh>HHH2</hhh>
  <hhh>HHH3</hhh>
  <hhh>HHH4</hhh>
  <!-- attributes -->
  <iii a1="123" a2="456" a3="789"/>
  <!-- attributes with text content-->
  <jjj a1="123" a2="456" a3="789">JJJ</jjj>
</root>

return $test

我正在使用 Saxon 解析器,带有这个命令行

java -cp Saxon-HE-9.8.0-8.jar net.sf.saxon.Query xml2json.xqy

但它仍然将 $test 变量作为 xml 返回,我错过了什么?

4

1 回答 1

3

您引用的 wikibook 文章不正确。根据相关规范,XSLT 和 XQuery Serialization 3.1,JSON 序列化方法对 XML 节点的处理如下

数据模型实例中的节点,通过参数指定的方法输出节点序列化结果,序列化为JSON字符串json-node-output-method。节点在序列化参数omit-xml-declaration设置为的情况下进行序列化,yes并且没有设置其他序列化参数。

换句话说,像 Saxon 这样的 XQuery 处理器应该将 XML 节点序列化为 JSON 字符串。

为了实现 wikibook 文章所承诺的目标,您需要将文档转换为地图和数组,或者转换为可以提供给xml-to-json()` 函数的中间格式。

于 2018-02-20T01:59:12.013 回答