我想更改XML节点的HTML内容,以便在XSL 1.0中用HTML标记替换某些BBCode。
我的XML看起来像这样:
<Article>
<Title>Article test</Title>
<Content>
<![CDATA[<p>Lorem Ipsum :</p><p>"[[Lorem ipsum dolor sit amet]] is a great tool !"</p>]]>
</Content>
</Article>
我想用“<em>
”替换“{[”by“</em>
”和“]]”。
我的XSL看起来像这样:
<?xml version="1.0" encoding = "ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"
media-type="text/html"
indent="yes"
omit-xml-declaration="yes"
encoding="ISO-8859-1"
doctype-public="-//W3C//DTD HTML 4.0 Strict//FR"
/>
<xsl:template match="/" >
<html>
<head>
<!--...-->
</head>
<body>
<xsl:for-each select="//Article[1]">
<h2><xsl:value-of select="Title"/></h2>
<div class="content"><xsl:apply-templates select="Content"/></div>
</xsl:for-each>
</body>
</html>
</xsl:template><!-- match=/ -->
<xsl:template match="Content">
<xsl:variable name="normaContenu"><xsl:value-of select="normalize-space(.)" /></xsl:variable>
<xsl:variable name="replacePatternStart"><![CDATA[<em>]]></xsl:variable>
<xsl:variable name="replacePatternEnd"><![CDATA[</em>]]></xsl:variable>
<xsl:variable name="contenuWithStartTags">
<xsl:call-template name="replace">
<xsl:with-param name="text" select="$normaContenu" />
<xsl:with-param name="replace" select="'[['" />
<xsl:with-param name="by" select="string($replacePatternStart)" />
</xsl:call-template>
</xsl:variable>
<xsl:call-template name="replace">
<xsl:with-param name="text" select="string($contenuWithStartTags)" />
<xsl:with-param name="replace" select="']]'" />
<xsl:with-param name="by" select="string($replacePatternEnd)" />
</xsl:call-template>
</xsl:template><!-- match=Content -->
<xsl:template name="replace">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="replace">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template><!-- name=replace -->
</xsl:stylesheet>
问题:“<em>
”实际上是“<em>
”。
如何强制XSL保留CDATA中定义的字符?
谢谢!
答案 0 :(得分:0)
您的代码不容易理解。替换实际上发生在&lt; xsl:value-of select =“...”/&gt;的某处。 - 这里使用&lt; xsl:value-of select =“...”disable-output-escaping =“yes”/&gt;代替。
@Pierre Morin:&lt; em&gt;插入时标签可能会被转义,因此disable-output-escaping显示无效。不同的浏览器在处理转换时会有所不同,可能会出现各种错误。尝试一个只包含输出的小解决方案,并在工作时将其装入。我建议使用像SaxonCE(免费客户端XSLT 1.0和2.0引擎,javascript)或libexslt(免费服务器端XSLT 1.0引擎,用c编写,广泛使用,例如php)的转换引擎
另一个提示:尽量不要在不同的代码中应用起始和结束标记。 XSLT不是为此而构建的。您可以使用元素而不会破坏它们,但这需要一些时间来了解XSLT。一旦你拿到它,它就会很强大。
我不知道这是否符合您的需求,但在&lt; em&gt;中添加$ text可以像
<xsl:template match="...">
<em>
<xsl:value-of select="$text"/>
</em>
</xsl:template>