我有这个 XML:
<root>
"countryList":
[
{
"countryName": "UK",
"countryId": "909",
"countryCapital": "london"
},
{
"countryName": "India",
"countryId": "910",
"countryCapital": "Delhi"
}
]
</root>
我需要迭代这个数组以获得以下 json 输出:
{
"countries":
[
{
"Name": "UK",
"Id": "909",
"Capital": "london"
},
{
"Name": "India",
"Id": "910",
"Capital": "Delhi"
}
]
}
有人可以帮助我实现同样的目标吗?赞赏!
到目前为止我尝试过的是:
<xsl:text>{ countries: </xsl:text>
<xsl: for-each = ="substring-before(substring-after(., '"countryList": '), ',')" >
<xsl:text>{ Name: </xsl:text>
<xsl:value-of select="substring-before(substring-after(., '"countryName": '), ',')"/>
<xsl:text>, Id: </xsl:text>
<xsl:value-of select="substring-before(substring-after(., '"countryId": '), ',')"/>
<xsl:text>} </xsl:text>
</xsl: for-each>
在 XSLT 1.0(或 XSLT 2.0)中使用字符串操作来处理 JSON 并不是一个可靠的过程。相同的 JSON 内容可以通过多种方式进行格式化(尤其是空白字符),并且设计用于处理一种形式的算法很容易在处理另一种形式时失败。
以下内容应该适用于您发布的示例。然而,更好的解决方案是迁移到 XSLT 3.0,其中可以本机摄取和处理 JSON。
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="/root">
<xsl:text>{ "countries"</xsl:text>
<xsl:call-template name="replace">
<xsl:with-param name="text" select="substring-after(., '"countryList"')"/>
</xsl:call-template>
<xsl:text>}</xsl:text>
</xsl:template>
<xsl:template name="replace">
<xsl:param name="text"/>
<xsl:param name="search-string"> "country</xsl:param>
<xsl:param name="replace-string"> "</xsl:param>
<xsl:choose>
<xsl:when test="contains($text, $search-string)">
<xsl:value-of select="substring-before($text, $search-string)"/>
<xsl:value-of select="$replace-string"/>
<xsl:call-template name="replace">
<xsl:with-param name="text" select="substring-after($text, $search-string)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>