XSLT需要将单个条件的内容转换为JSON

时间:2013-08-27 14:16:31

标签: xml xslt

我有一个输入

<xml>
<p>"It may be recalled that the foggy family law suit in Jarndyce v Jarndyce dragged on before the Lord Chancellor for generations until nothing was left for the parties to take. </p>
</xml> 

我需要将其转换为如下[我的意思是,json格式]:

"content": "<p>&#x0022;It may be recalled that the foggy family law suit in Jarndyce v Jarndyce dragged on before the Lord Chancellor for generations until nothing was left for the parties to take&#x0022;. </p>"

我的意思是,在这里,我只需要段落内的引号。除了这里,它不应该改变。 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这是一个XSLT 1.0解决方案 - 使用递归模板进行字符串替换:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template name="replace">
    <xsl:param name="str"/>
    <xsl:param name="from"/>
    <xsl:param name="to"/>
    <xsl:choose>
      <xsl:when test="contains($str,$from)">
        <xsl:value-of select="concat(substring-before($str,$from),$to)"/>
        <xsl:call-template name="replace">
          <xsl:with-param name="str" select="substring-after($str,$from)"/>
          <xsl:with-param name="from" select="$from"/>
          <xsl:with-param name="to" select="$to"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$str"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="p">
    "content" : "&lt;p&gt;
    <xsl:call-template name="replace">
      <xsl:with-param name="str" select="."/>
      <xsl:with-param name="from" select="'&quot;'"/>
      <xsl:with-param name="to" select="'&amp;#x0022;'"/>
    </xsl:call-template>
    &lt;/p&gt;"
  </xsl:template>

  <xsl:template match="/">
    <xsl:apply-templates />
  </xsl:template>

</xsl:stylesheet>

答案 1 :(得分:0)

另一个xsl 1.0解决方案

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes" method="text"/>
  <xsl:template match="/xml/p">
      <xsl:text>"content":"&lt;p&gt;</xsl:text>
      <xsl:call-template name="replace">
        <xsl:with-param name="substring" select="text()"/>
      </xsl:call-template>
      <xsl:text>&lt;/p&gt;"</xsl:text>
  </xsl:template>
  <xsl:template name="replace">
    <xsl:param name="substring"/> 
      <xsl:choose>
        <xsl:when test="contains($substring,'&quot;')">
          <xsl:value-of select="substring-before($substring,'&quot;')"/>
          <xsl:text>&amp;#x0022;</xsl:text>
          <xsl:call-template name="replace">
            <xsl:with-param name="substring" select="substring-after($substring,'&quot;')"/>
          </xsl:call-template>  
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$substring"/>
        </xsl:otherwise>
      </xsl:choose> 
  </xsl:template> 
</xsl:stylesheet>

可以测试here

相关问题