2013-08-27 24 views
1

我有一个输入,因为这XSLT需要与单个条件的内容转换成JSON

<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>" 

我的意思是,在这里,我只需要段落内的报价。除了这里,它不应该改变。 任何想法?

回答

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> 
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

+0

@jwerde:有用。我用xslt 2.0试过这个。链接也很好。谢谢 – Sakthivel