11

如何创建相同的 XML 表,但删除每个属性的前导和尾随空格?(使用 XSLT 2.0)

从这里开始:

<node id="DSN ">
    <event id=" 2190 ">
        <attribute key=" Teardown"/>
        <attribute key="Resource "/>
    </event>
</node>

对此:

<node id="DSN">
    <event id="2190">
        <attribute key="Teardown"/>
        <attribute key="Resource"/>
    </event>
</node>

我想我更喜欢使用该normalize-space()功能,但无论如何都可以。

4

2 回答 2

21

normalize-space()不仅会删除前导和尾随空格,还会安装一个空格字符来代替任何连续的空格字符序列。

正则表达式可用于处理前导和尾随空格:

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

  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*">
    <xsl:attribute name="{local-name()}" namespace="{namespace-uri()}">
      <xsl:value-of select="replace(., '^\s+|\s+$', '')"/>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>
于 2013-05-15T19:58:39.383 回答
7

这应该这样做:

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

  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*">
    <xsl:attribute name="{name()}">
      <xsl:value-of select="normalize-space()"/>
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

这也与 XSLT 1.0 兼容。

在您的示例输入上运行时,结果是:

<node id="DSN">
  <event id="2190">
    <attribute key="Teardown" />
    <attribute key="Resource" />
  </event>
</node>

这里要注意的一件事是normalize-space()将属性值中的任何空格转换为单个空格,因此:

<element attr="   this    is an
                   attribute   " />

会改成这样:

<element attr="this is an attribute" />

如果您需要按原样将空格保留在值内,请参阅 Gunther 的回答。

于 2013-05-15T19:23:30.263 回答