XSLT:在text元素中,如何用空格替换换行符(<br/>)?

时间:2015-08-18 17:26:49

标签: xslt xml-parsing xslt-1.0

注意:我在OS X Yosemite上使用xsltproc

XSLT转换的源内容是HTML。一些 文本节点包含换行符(&lt; br /&gt;)。在转型中 content(一个XML文件),我希望将换行符转换为空格。

例如,我有:

<div class="location">London<br />Hyde Park<br /></div>

我想像这样转换这个元素:

<xsl:element name="location">
  <xsl:variable name="location" select="div[@class='location']"/>
  <xsl:value-of select="$location"/>
</xsl:element>

&lt; br /&gt;会发生什么?只是删除了输出:

<location>LondonHyde Park</location>

我还有其他模板:

<xsl:template match="node()|script"/>

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

在此处转换&lt; br /&gt;&#需要哪些XSLT操作 到一个空间?

1 个答案:

答案 0 :(得分:0)

我会使用xsl:apply-templates代替xsl:value-of并添加模板来处理<br/>

您还需要修改<xsl:template match="node()|script"/>,因为node()也会选择文本节点。如果需要,您可以将node()替换为processing-instruction()|comment(),但无论如何都不会默认输出。

这是一个有效的例子:

<强>输入

<div class="location">London<br />Hyde Park<br /></div>

XSLT 1.0

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

    <xsl:template match="script"/>

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

    <xsl:template match="div[@class='location']">
        <location><xsl:apply-templates/></location>
    </xsl:template>

    <xsl:template match="br">
        <xsl:text> </xsl:text>
    </xsl:template>

</xsl:stylesheet>

<强>输出

<location>London Hyde Park </location>

如果你不想要尾随空格,你可以......

  • xsl:apply-templates放入变量($var)并在normalize-space()中使用xsl:value-of。喜欢:<xsl:value-of select="normalize-space($var)"/>
  • 更新br元素的匹配项。喜欢:br[not(position()=last())]