我想使用 XSLT 将一些 XML 转换为 JSON。
XML 如下所示:
<DATA_DS>
<G_1>
<ORGANIZATION_NAME>My Company 1</ORGANIZATION_NAME>
<ORGANIZATIONID>901</ORGANIZATIONID>
<ITEMNUMBER>20001</ITEMNUMBER>
<ITEMDESCRIPTION>Item Description 1</ITEMDESCRIPTION>
</G_1>
<G_1>
<ORGANIZATION_NAME>My Company 1</ORGANIZATION_NAME>
<ORGANIZATIONID>901</ORGANIZATIONID>
<ITEMNUMBER>20002</ITEMNUMBER>
<ITEMDESCRIPTION>Item Description 2</ITEMDESCRIPTION>
</G_1>
<G_1>
<ORGANIZATION_NAME>My Company 1</ORGANIZATION_NAME>
<ORGANIZATIONID>901</ORGANIZATIONID>
<ITEMNUMBER>20003</ITEMNUMBER>
<ITEMDESCRIPTION>Item Description 3</ITEMDESCRIPTION>
</G_1>
</DATA_DS>
我希望 JSON 如下所示:
[
{
"Item_Number":"20001",
"Item_Description":"Item Description 1"
},
{
"Item_Number":"20002",
"Item_Description":"Item Description 2"
},
{
"Item_Number":"20003",
"Item_Description":"Item Description 3"
}
]
推荐的方法是什么?
我正在考虑两种方法:
尝试使用fn:xml-to-json
函数,定义为https://www.w3.org/TR/xpath-functions-31/#func-xml-to-json https://www.w3.org/TR/xpath-functions-31/#func-xml-to-json。但据我了解,输入 XML 必须遵循以下定义的特定格式:https://www.w3.org/TR/xpath-functions-31/schema-for-json.xsd https://www.w3.org/TR/xpath-functions-31/schema-for-json.xsd。我还需要输出 JSON 中的字段名称具体为“Item_Number”和“Item_Description”。
手动编码方括号和大括号字符“[”、“]”、“{”和“}”以及字段名称“Item_Number”和“Item_Description”。然后使用标准函数列出值并确保正确处理任何特殊字符。例如,“&”字符应正常出现在 JSON 输出中。
推荐的方法是什么,或者是否有我没有考虑过的更好的方法?
我会采用第一种方法,但首先将给定的输入转换为预期的 XML 格式xml-to-json()
功能。这可能是这样的:
XSLT 3.0
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/2005/xpath-functions">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="/G_1">
<!-- CONVERT INPUT TO XML FOR JSON -->
<xsl:variable name="xml">
<array>
<xsl:for-each-group select="*" group-starting-with="ORGANIZATION_NAME">
<map>
<string key="Item_Number">
<xsl:value-of select="current-group()[self::ITEMNUMBER]"/>
</string>
<string key="Item_Description">
<xsl:value-of select="current-group()[self::ITEMDESCRIPTION]"/>
</string>
</map>
</xsl:for-each-group>
</array>
</xsl:variable>
<!-- OUTPUT -->
<xsl:value-of select="xml-to-json($xml)"/>
</xsl:template>
</xsl:stylesheet>
Demo: https://xsltfiddle.liberty-development.net/bFWR5DQ https://xsltfiddle.liberty-development.net/bFWR5DQ
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)