跳转到内容

XQuery/将 XML 转换为 JSON

来自维基教科书,开放的书籍,为开放的世界

您可以使用 JSON 输出方法将 XML 转换为 JSON 格式。(有关本文的重要说明,请参见 https://stackoverflow.com/questions/48876292/how-to-use-the-xslt-xquery-serialization-namespace-to-export-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

示例输出

[编辑 | 编辑源代码]
{
    "aaa": "AAA",
    "bbb": "BBB",
    "ccc": "CCC",
    "ddd": {"eee": {"fff": {"ggg": "GGG"}}},
    "hhh": [
        "HHH1",
        "HHH2",
        "HHH3",
        "HHH4"
    ],
    "iii": {
        "a1": "123",
        "a2": "456",
        "a3": "789"
    },
    "jjj": {
        "a1": "123",
        "a2": "456",
        "a3": "789",
        "#text": "JJJ"
    }
}
华夏公益教科书