使用xsl从xml中去掉空格



我有一个xml,我正在使用xslt转换。xml看起来像这样

<Function name="Add" returnType="Integer">
<Description>
// Returns the sum of the input parameters
// param [out]    result
// param [in]     input 1
// param [in]     input 2
// return         error        Ok=0, Warning=1, Error=2
</Description>
</Function>

我想去掉description标签下每行前的空格。

当前输出:

// Returns the sum of the input parameters
// param [out]    result
// param [in]     input 1
// param [in]     input 2
// return         error        Ok=0, Warning=1, Error=2

预期输出:

// Returns the sum of the input parameters
// param [out]    result
// param [in]     input 1
// param [in]     input 2
// return         error        Ok=0, Warning=1, Error=2

我有一个xslt,我试图翻译输入

<xsl:value-of select="translate(Description, '    ','')" />

不幸的是,它删除了Description中的所有空格。

我也尝试了<xsl:strip-space elements="*"/>并规范化

<xsl:variable name="description" select="Description"/>
<varoutput>
<xsl:value-of select= "normalize-space($description)"/>
</varoutput>

但是运气不好。如果有人能帮助我,我能做些什么。

这是XSl 1.0,因为我正在使用schemasmicrosoft.com:xslt

要删除每行开头的空白,必须将文本分割为单独的行,并依次处理每行。要在纯XSLT 1.0中做到这一点,需要使用递归命名模板:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Description">
<xsl:copy>
<xsl:call-template name="process-lines">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
</xsl:copy> 
</xsl:template>
<xsl:template name="process-lines">
<xsl:param name="text"/>
<xsl:param name="delimiter" select="'&#10;'"/>
<xsl:variable name="line" select="substring-before(concat($text, $delimiter), $delimiter)" />
<xsl:variable name="first-char" select="substring(normalize-space($line), 1, 1)" />
<!-- output -->
<xsl:value-of select="$first-char"/>
<xsl:value-of select="substring-after($line, $first-char)"/>
<!-- recursive call -->
<xsl:if test="contains($text, $delimiter)">
<xsl:value-of select="$delimiter"/>
<xsl:call-template name="process-lines">
<xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

当应用到你的输入示例时,这将产生:

结果

<?xml version="1.0" encoding="UTF-8"?>
<Function name="Add" returnType="Integer">
<Description>
// Returns the sum of the input parameters
// param [out]    result
// param [in]     input 1
// param [in]     input 2
// return         error        Ok=0, Warning=1, Error=2
</Description>
</Function>

最新更新