2013-12-18 18 views
6

XSLTを使用してXMLをJSONに変換しようとしています。以下は私のXMLとXSLTのコードです。XSLTを使用してXMLをJSONに変換する際の問題

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ファイル: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> 

出力:

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

問題は、余分なカンマで( '')があるということです配列内の最後のオブジェクトの終わり。 XSLTでそれを避ける方法はありますか?

答えて

11

xmlに別の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> 
<xsl:if test="./following-sibling::cd">,</xsl:if>

だからあなたのスタイルシートがそのようになります。

関連する問題