使用XSLT将XML转换为JSON时出现问题 [英] Problems converting XML to JSON using XSLT

查看:261
本文介绍了使用XSLT将XML转换为JSON时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用XSLT将XML转换为JSON.以下是我的XML和XSLT代码.

I am trying to convert an XML to JSON using XSLT. Following are my XML and XSLT code.

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中发生这种情况?

The problem is that there is an extra comma(',') at the end of the last object in the array. Is there a way to avoid that in XSLT ?

推荐答案

如果您的xml中还有另一个cd元素,则只写逗号.

Only write the comma if there is another cd element in your xml.

因此,基本上,您必须将逗号包装在xsl:if语句中,如下所示:<xsl:if test="./following-sibling::cd">,</xsl:if>

So basically you have to wrap that comma in a xsl:if statement like this: <xsl:if test="./following-sibling::cd">,</xsl:if>

因此您的样式表应如下所示:

So your stylesheet will look something like that:

<?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>

这篇关于使用XSLT将XML转换为JSON时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆