XML to JSON Transformation in XSLT 3.0 [closed]

送分小仙女□ 提交于 2019-12-20 07:48:33

问题


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.

Example XML is:

<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>

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

}}

Thanks in Advance


回答1:


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>

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

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.



来源:https://stackoverflow.com/questions/45739445/xml-to-json-transformation-in-xslt-3-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!