如何仅使用XSLT去除回车?

时间:2011-07-02 01:15:41

标签: xml xslt xpath

我有一个xml代码可以有两种形式:

表单1

<?xml version="1.0">
<info>
</info>

表格2

<?xml version="1.0">
<info>
  <a href="http://server.com/foo">bar</a>
  <a href="http://server.com/foo">bar</a>
</info>

从循环中我读取每种形式的xml并将其传递给xslt样式表。

XSLT代码

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

    <xsl:template match="*|@*|text()">
       <xsl:apply-templates select="/info/a"/>
    </xsl:template> 

    <xsl:template match="a">
       <xsl:value-of select="concat(text(), ' ', @href)"/>
       <xsl:text>&#13;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

我得到了这个:


bar http://server.com/foo
bar http://server.com/foo

如何使用仅限XSLT 删除第一个空行?

3 个答案:

答案 0 :(得分:2)

  

从循环中我读取每种形式的xml并将其传递给xslt样式表。

可能来自您的应用程序在空表单(表单1)上执行样式表会导致此问题。尝试仅通过执行样式表来处理此问题,无论表单是否为空。

此外,您可能希望将样式表更改为:

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

    <xsl:output method="text"/>
    <xsl:strip-space elements="*" />

    <xsl:template match="info/a">
        <xsl:value-of select="concat(normalize-space(.), 
            ' ',
            normalize-space(@href))"/>
            <xsl:if test="follwing-sibling::a">
             <xsl:text>&#xA;</xsl:text>
            </xsl:if>
    </xsl:template>

</xsl:stylesheet>

使用normalize-space()确保您的输入数据没有不需要的空格。

答案 1 :(得分:1)

它可能取决于您正在使用的XSL处理器,但您是否尝试过以下操作?

<xsl:output method="text" indent="no" />

答案 2 :(得分:1)

您想要使用文本输出方法,只处理您想要的节点,而不是在最后一个之后(或在下面的解决方案之前的第一个之前)输出新行

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

  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

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

  <xsl:template match="a">
    <xsl:if test="not(position() = 1)" xml:space="preserve">&#xA;</xsl:if>
    <xsl:value-of select="concat(text(), ' ', @href)"/>
  </xsl:template>

您需要xml:space指令上的xsl:text,以便在读取样式表时不会对空格进行规范化。