XSLT 3.0中的XML到JSON的转换 [英] XML to JSON Transformation in XSLT 3.0

查看:163
本文介绍了XSLT 3.0中的XML到JSON的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to convert XML data to JSON in XSLT 3.0 using xml-to-json function. Can any one please provide me the Xslt 3.0 for the below requirement.

示例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输出是:

My expected json output is:

{"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;"
}

}}

预先感谢

推荐答案

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

You need to transform your XML into the XML vocabulary expected by the xml-to-json function, which you can do using template rules such as

<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函数.

and then pass the result of this transformation to the xml-to-json function.

详细信息取决于您要对名称空间执行的操作,如何检测元素/属性应被视为数字或布尔值,是否要为空元素生成null或"等.

The detail will depend on what you want to do about namespaces, how you want to detect that elements/attributes should be treated as numeric or boolean, whether you want to generate null or "" for empty elements, etc.

这篇关于XSLT 3.0中的XML到JSON的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆