【问题标题】:Writing JSON with XSLT使用 XSLT 编写 JSON
【发布时间】:2010-05-14 21:41:59
【问题描述】:

我正在尝试编写 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>

【问题讨论】:

    标签: json xslt


    【解决方案1】:

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

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

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

    【讨论】:

    • 恕我直言,position() 是 XSLT 唯一的天才特性。
    【解决方案2】:

    将 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,因此可能需要替换单引号。

    【讨论】:

      【解决方案3】:

      为什么不改用 Sitecore Item Web API?它在 SDN 上可用,并作为一个简单的插件安装。安装后,您可以使用 REST 以 JSON 格式获取项目。可以搜索项目,您可以为通过 JSON 提供的各个字段设置安全性。此外,您实际上可以使用 REST 和 JSON 创建、删除和更新 Sitecore 项目。

      【讨论】:

      • 当然,在您提出问题时,Item Web API 不可用 :-)
      • 此评论是否与帖子 (stackoverflow.com/questions/2837809/writing-json-with-xslt) 相关?如果是这样,是什么让您认为这是一个 Sitecore 问题 - 如果不是,那么某处的 SO 中一定存在错误并且它变得混乱。
      猜你喜欢
      • 2020-08-12
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      相关资源
      最近更新 更多