使用 XSLT 编写 JSON [英] Writing JSON with XSLT

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

问题描述

我正在尝试编写 XSLT 以将特定网页转换为 JSON.下面的代码演示了 Ruby 如何进行这种转换,但 XSLT 没有生成有效的 JSON(数组中的逗号太多了)——有谁知道如何编写 XSLT 来生成有效的 JSON?

I'm trying to write XSLT to transform a specific web page to JSON. The following code demonstrates how Ruby would do this conversion, but the XSLT doesn't generate valid JSON (there's one too many commas inside the array) - anyone know how to write XSLT to generate valid JSON?

require 'rubygems'
require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open('http://bbc.co.uk/radio1/playlist'))
xslt = Nokogiri::XSLT(DATA.read)

puts out = xslt.transform(doc)

# Now follows the XSLT
__END__
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
    <xsl:output method="text" encoding="UTF-8" media-type="text/plain"/>

    <xsl:template match="/">
        [
        <xsl:for-each select="//*[@id='playlist_a']//div[@class='artists_and_songs']//ul[@class='clearme']">
            {'artist':'<xsl:value-of select="li[@class='artist']" />','track':'<xsl:value-of select="li[@class='song']" />'},
        </xsl:for-each>
        ]
    </xsl:template>
</xsl:stylesheet>

推荐答案

省略 for-each 行内的逗号并添加:

Omit the comma from the line inside the for-each and add:

<xsl:if test="position() != last()">,</xsl:if>

这将为除最后一项之外的每一项添加一个逗号.

This will add a comma to each item except the last one.

这篇关于使用 XSLT 编写 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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