2010-05-14 37 views
13

我在編寫XSLT來將特定的網頁轉換爲JSON。下面的代碼演示了Ruby如何進行這種轉換,但XSLT不會生成有效的JSON(數組中有太多逗號) - 任何人都知道如何編寫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> 

回答

19

省略了逗號從行內for-each並添加:

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

這將逗號添加到每個項目除了最後一個。

+3

恕我直言,position()是XSLT唯一的閃現天才功能。 – 2010-05-14 21:47:59

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> 

此外,歌手和歌曲的值可以打破你的JSON中是否含有單引號,替換單引號可能是必要的。

0

爲什麼不使用Sitecore Item Web API呢?它在SDN上可用,並作爲一個簡單的插件安裝。安裝後,您可以使用REST將項目恢復爲JSON。可以搜索項目,並且可以爲通過JSON提供的各個字段設置安全性。更進一步,您實際上可以使用REST和JSON創建,刪除和更新Sitecore項目。

+1

關閉當然,在你的問題時,項目Web API不可用:-) – Zooking 2013-02-28 08:36:23

+0

這篇評論與帖子相關(http://stackoverflow.com/questions/2837809/writing-json-with-xslt)?如果是這樣,是什麼讓你認爲這是一個Sitecore問題 - 如果不是這樣,那麼在某個地方肯定會出現一個bug,它會變得混亂。 – 2016-09-01 02:51:45