我正在尝试使用XSLT将XML转换为JSON。以下是我的XML和XSLT代码。
XML档案:
<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Subrayana kathe</title>
<artist>Subba</artist>
<country>India</country>
<price>30</price>
<year>1986</year>
</cd>
</catalog>
XSLT文件:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
{
"catalog":[
<xsl:for-each select="catalog/cd">
{"title":"
<xsl:value-of select="title" />
",
"artist":"
<xsl:value-of select="artist" />
"},
</xsl:for-each>
]
}
</xsl:template>
</xsl:stylesheet>
XSLT的输出:
{
"catalog":[
{
"title":"Empire Burlesque",
"artist":"Bob Dylan"
},
{
"title":"Subrayana kathe",
"artist":"Subba"
},(Problematic comma)
]
}
问题在于数组中最后一个对象的末尾有一个额外的逗号(',')。有没有办法避免在XSLT中发生这种情况?
如果cd
您的xml中还有其他元素,则仅写逗号。
因此,基本上,您必须用以下xsl:if
语句将逗号换行:<xsl:if test="./following-sibling::cd">,</xsl:if>
因此,您的样式表将如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
{
"catalog":[
<xsl:for-each select="catalog/cd">
{"title":"
<xsl:value-of select="title" />
",
"artist":"
<xsl:value-of select="artist" />
"}<xsl:if test="./following-sibling::cd">,</xsl:if>
</xsl:for-each>
]
}
</xsl:template>
</xsl:stylesheet>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句