【问题标题】:Problems converting XML to JSON using XSLT使用 XSLT 将 XML 转换为 JSON 的问题
【发布时间】:2013-12-18 12:32:25
【问题描述】:

我正在尝试使用 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 中避免这种情况?

【问题讨论】:

    标签: xml json xslt


    【解决方案1】:

    只有在你的 xml 中有另一个 cd 元素时才写逗号。

    所以基本上你必须将逗号包装在 xsl:if 语句中,如下所示:&lt;xsl:if test="./following-sibling::cd"&gt;,&lt;/xsl:if&gt;

    所以你的样式表看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多