如何在XSLT中将双引号替换为字符串'\“'?

Tom*_*ise 2 xml xslt

我有一个XML,其中双引号应替换为字符串“”。

例如:<root><statement1><![CDATA[<u>teset "message"here</u>]]></statement1></root>

所以输出应该是 <root><statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1></root>

有人可以解释如何做到这一点吗?

Dim*_*hev 5

一,XSLT 1.0解决方案

此转换

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"
 cdata-section-elements="statement1"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pPattern">"</xsl:param>
 <xsl:param name="pReplacement">\"</xsl:param>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="statement1/text()" name="replace">
  <xsl:param name="pText" select="."/>
  <xsl:param name="pPat" select="$pPattern"/>
  <xsl:param name="pRep" select="$pReplacement"/>

 <xsl:choose>
  <xsl:when test="not(contains($pText, $pPat))">
   <xsl:copy-of select="$pText"/>
  </xsl:when>
  <xsl:otherwise>
   <xsl:copy-of select="substring-before($pText, $pPat)"/>
   <xsl:copy-of select="$pRep"/>
   <xsl:call-template name="replace">
    <xsl:with-param name="pText" select=
         "substring-after($pText, $pPat)"/>
    <xsl:with-param name="pPat" select="$pPat"/>
    <xsl:with-param name="pRep" select="$pRep"/>
   </xsl:call-template>
  </xsl:otherwise>
 </xsl:choose>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

当应用于提供的XML文档时

<root>
    <statement1><![CDATA[<u>teset "message"here</u>]]></statement1>
</root>
Run Code Online (Sandbox Code Playgroud)

产生想要的正确结果

<root>
   <statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1>
</root>
Run Code Online (Sandbox Code Playgroud)

二。XSLT 2.0解决方案

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"
 cdata-section-elements="statement1"/>

 <xsl:param name="pPat">"</xsl:param>
 <xsl:param name="pRep">\\"</xsl:param>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

  <xsl:template match="statement1/text()">
   <xsl:sequence select="replace(.,$pPat, $pRep)"/>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

当应用于相同的XML文档(如上所述)时,会产生相同的正确结果

<root>
      <statement1><![CDATA[<u>teset \"message\"here</u>]]></statement1>
</root>
Run Code Online (Sandbox Code Playgroud)