删除文本节点中的空白区域的问题

时间:2012-08-22 11:56:08

标签: xml xslt xpath

在删除文本节点中的空白区域时遇到一些问题。这是我使用的代码,但仍然没有空格。

 <xsl:output indent="yes" method="xml"/> 
 <xsl:template match="/">

    <Address>  <xsl:apply-templates/> </Address>
 </xsl:template>

 <xsl:template match="Address/Rowinfo ">

     <xsl:copy>
        <xsl:copy-of select="LocatorDesignator"/>
        <xsl:copy-of select="LocatorName"/>

    </xsl:copy>
    </xsl:template>


 <xsl:template match="Address/Rowinfo/LocatorDesignator">

    <xsl:value-of select = "normalize-space(LocatorDesignator)"/> 
    <xsl:apply-templates/>
     </xsl:template>

 <xsl:template match="Address/Rowinfo/LocatorName">

    <xsl:value-of select = "normalize-space(LocatorName)"/> 
    <xsl:apply-templates/>
 </xsl:template>
 </xsl:stylesheet>

它会产生相同的结果。这是一个示例xml数据,其文本节点中包含白色空间。

<Address>
<Rowinfo>
<Locator>mr oga,    Ade  </Locator>
<LocatorDesignator>Dwelling(Part Of),   Null </LocatorDesignator>
</Rowinfo>

我的预期输出是

   <Locator>mr oga, Ade</Locator>
  <LocatorDesignator>Dwelling(Part Of),Null</LocatorDesignator>

2 个答案:

答案 0 :(得分:2)

从文本节点中删除不需要的空间的一种众所周知的方法是使用

<强> normalize-space()

功能

从XML文档中删除空白文本节点的另一种补充方法是 XSLT instruction

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

删除任何其他更具体的模板不匹配的文本节点的第三种方法是使用以下模板:

<xsl:template match="text()"/>

这个功能更强大(不明智的使用会导致想要的文本节点在输出中被“删除”)。

人们通常使用这三种方法的组合来删除不需要的空白和文本节点。

答案 1 :(得分:0)

您的模板未使用

而不是

<xsl:copy-of select="LocatorDesignator"/> 

<xsl:apply-templates select="LocatorDesignator"/> 

或者如JWiley建议的那样,删除带有translate

的空格
<xsl:template match="Address/Rowinfo/LocatorDesignator">  
    <xsl:value-of select = "translate(.,' ', '')"/>  
    <xsl:apply-templates/> 
</xsl:template> 

或者您有多种方式可以到达罗马:

 <xsl:copy-of select="translate(LocatorDesignator,' ','')"/>