我有一些输入XML,如下所示:
<list>
<document>
<content name="url">some_url_here</content>
<content name="title">document title</content>
<content name="state">CA</content>
<content name="state">NY</content>
</document>
<document>
<content name="url">some_other_url_here</content>
<content name="title">document2 title</content>
<content name="title">duplicate title</content>
<content name="state">OH</content>
<content name="state">PA</content>
<content name="state">FL</content>
</document>
</list>
最终目标是生成如下所示的JSON:
{
"list": [
{
"contents": {
"url": "some_url_here",
"title": "document title",
"state": [
"CA",
"NY"
]
}
},
{
"contents": {
"url": "some_other_url_here",
"title": "document2 title",
"state": [
"OH",
"PA",
"FL"
]
}
}
]
}
这就是我一直努力工作的原因。我有一个流氓逗号的问题是无效的json。我相信这是因为XML中的内容顺序可能与XSL键中的顺序不同,所以我无法可靠地判断是否有前一项。
<xsl:template match="document">
<xsl:variable name="doc" select="." />
<xsl:call-template name="indent" />
<xsl:text> "contents":{</xsl:text>
<!-- get unique content names -->
<xsl:for-each select="//content[generate-id() = generate-id(key('nameDistinct', @name)[1])]">
<xsl:sort select="@name"/>
<xsl:variable name="name" select="@name" />
<xsl:variable name="count" select="count($doc/content[@name=$name])" />
<xsl:variable name="contents" select="$doc/content[@name=$name]" />
<xsl:variable name="preceeding" select="$doc/content[@name=$name]/preceding-sibling::content/text()!=''"/>
<xsl:if test="position() > 1 and $preceeding > 0">
<xsl:text>,</xsl:text>
</xsl:if>
<xsl:if test="$count > 0">
<xsl:call-template name="indent" />
</xsl:if>
<xsl:choose>
<xsl:when test="$count > 1">
<!-- handle multiple contents -->
</xsl:when>
<xsl:when test="$count = 1">
<!-- handle single content -->
</xsl:when>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
我正在努力解决逗号问题,但我认为我可能正在接近这个完全错误。我也仅限于XSLT 1.0。