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