使用XSLT将XML转换为JSON的问题

CCo*_*der 6 xml xslt json

我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

XSLT的输出:

{
   "catalog":[
      {
         "title":"Empire Burlesque",
         "artist":"Bob Dylan"
      },
      {
         "title":"Subrayana kathe",
         "artist":"Subba"
      },(Problematic comma)
   ]
}
Run Code Online (Sandbox Code Playgroud)

问题是在数组中最后一个对象的末尾有一个额外的逗号(',').有没有办法在XSLT中避免这种情况?

Mat*_*ias 11

只有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>
Run Code Online (Sandbox Code Playgroud)