如何仅使用XSLT去除回车?

Ste*_*han 5 xml xslt xpath

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

表格1

<?xml version="1.0">
<info>
</info>
Run Code Online (Sandbox Code Playgroud)

表格2

<?xml version="1.0">
<info>
  <a href="http://server.com/foo">bar</a>
  <a href="http://server.com/foo">bar</a>
</info>
Run Code Online (Sandbox Code Playgroud)

从循环中我读取每种形式的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>
Run Code Online (Sandbox Code Playgroud)

我得到了这个:


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

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

Emi*_*ggi 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>
Run Code Online (Sandbox Code Playgroud)

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