用XSLT编写JSON

JP.*_*JP. 14 xslt json

我正在尝试编写XSLT以将特定网页转换为JSON.下面的代码演示了Ruby如何进行这种转换,但是XSLT没有生成有效的JSON(数组中有太多逗号) - 任何人都知道如何编写XSLT来生成有效的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>
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 20

从里面的行中省略逗号for-each并添加:

<xsl:if test="position() != last()">,</xsl:if>
Run Code Online (Sandbox Code Playgroud)

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

  • 恕我直言,position()是XSLT唯一的天才闪现功能. (3认同)

Tom*_*lak 5

将XSLT拆分为单独的模板可以提高可读性.

<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:text>[</xsl:text>
    <xsl:apply-templates select="//div[@id='playlist_a']//ul[@class='clearme']" />
    <xsl:text>]</xsl:text>
  </xsl:template>

  <xsl:template match="ul">
    <xsl:text>{'artist':'</xsl:text><xsl:value-of select="li[@class='artist']" />
    <xsl:text>','track':'</xsl:text><xsl:value-of select="li[@class='song']" />
    <xsl:text>'}</xsl:text>
    <xsl:if test="position() &lt; last()">,</xsl:if>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

此外,艺术家和歌曲的值如果包含单引号就会破坏您的JSON,可能需要替换单引号.