-1

我正在尝试使用 xml-to-json 函数将 XML 数据转换为 XSLT 3.0 中的 JSON。任何人都可以为我提供满足以下要求的 Xslt 3.0。

示例 XML 是:

<widget>
<debug>on</debug>
<window title="Sample Konfabulator Widget">
    <name>main_window</name>
    <width>500</width>
    <height>500</height>
</window>
<image src="Images/Sun.png" name="sun1">
    <hOffset>250</hOffset>
    <vOffset>250</vOffset>
    <alignment>center</alignment>
</image>
<text data="Click Here" size="36" style="bold">
    <name>text1</name>
    <hOffset>250</hOffset>
    <vOffset>100</vOffset>
    <alignment>center</alignment>
    <onMouseUp>
        sun1.opacity = (sun1.opacity / 100) * 90;
    </onMouseUp>
</text>

我预期的 json 输出是:

{"widget": {
"debug": "on",
"window": {
    "title": "Sample Konfabulator Widget",
    "name": "main_window",
    "width": 500,
    "height": 500
},
"image": { 
    "src": "Images/Sun.png",
    "name": "sun1",
    "hOffset": 250,
    "vOffset": 250,
    "alignment": "center"
},
"text": {
    "data": "Click Here",
    "size": 36,
    "style": "bold",
    "name": "text1",
    "hOffset": 250,
    "vOffset": 100,
    "alignment": "center",
    "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}

}}

提前致谢

4

1 回答 1

1

您需要将您的 XML 转换为 xml-to-json 函数所期望的 XML 词汇表,您可以使用模板规则来执行此操作,例如

<xsl:template match="*[*|@*]" mode="to-json">
  <fn:map key="{local-name()}">
    <xsl:apply-templates select="@*, *" mode="to-json"/>
  </fn:map>
</xsl:template>

<xsl:template match="@* | *[not(*)]" mode="to-json">
  <fn:string key="{local-name()}">
    <xsl:value-of select="."/>
  </fn:string>
</xsl:template>

然后将此转换的结果传递给 xml-to-json 函数。

详细信息将取决于您想对命名空间做什么、如何检测元素/属性应被视为数字还是布尔值、是否要为空元素生成 null 或 "" 等。

于 2017-08-17T17:03:40.940 回答