如何通过XSLT将指定XML转换为目标JSON字符串?
用XSLT将XML转换为指定格式的JSON字符串
输入XML
<?xml version="1.0" encoding="UTF-8"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10</price> <year>1985</year> </cd> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>11</price> <year>1985</year> </cd> </catalog>
当前使用的XSLT
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:template match="/"> { "Details": { "your_requested_data" : "{ <xsl:for-each select='catalog/cd' ><xsl:choose><xsl:when test='position() = last()'>\"data\" : [{\"price\":\"<xsl:value-of select='price' />\"}]</xsl:when></xsl:choose></xsl:for-each>}" } } </xsl:template> </xsl:stylesheet>
期望输出
{ "Details": { "your_requested_data" : "{ \"data\" : [{\"price\":\"10\"},{\"price\":\"11\"}]}" } }
修正后的XSLT实现
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" /> <xsl:template match="/"> { "Details": { "your_requested_data" : "{ \"data\" : [{ <xsl:for-each select='catalog/cd'> {\"price\":\"<xsl:value-of select='price' />\"}<xsl:if test="position() != last()">,</xsl:if> </xsl:for-each> }]}" } } </xsl:template> </xsl:stylesheet>
关键修改说明
- 将
data数组的起始结构移到循环外部,不再只处理最后一个<cd>节点 - 遍历所有
<cd>节点,为每个节点生成对应的{"price":"xxx"}格式内容 - 通过
<xsl:if>判断,给除最后一项外的每个价格节点添加逗号,保证JSON数组格式合法 - 调整了换行和空格位置,匹配你需要的输出格式
内容的提问来源于stack exchange,提问作者chandan vishwakarma
相关产品推荐
相关产品推荐

