XSLT删除所有属性的前导和尾随空格

sma*_*oun 11 xml xslt xslt-2.0

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

从这里开始:

<node id="DSN ">
    <event id=" 2190 ">
        <attribute key=" Teardown"/>
        <attribute key="Resource "/>
    </event>
</node>
Run Code Online (Sandbox Code Playgroud)

对此:

<node id="DSN">
    <event id="2190">
        <attribute key="Teardown"/>
        <attribute key="Resource"/>
    </event>
</node>
Run Code Online (Sandbox Code Playgroud)

我想我更喜欢使用这个normalize-space()功能,但无论如何都有效.

Gun*_*her 19

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>
Run Code Online (Sandbox Code Playgroud)


JLR*_*she 8

这应该这样做:

<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>
Run Code Online (Sandbox Code Playgroud)

这也是XSLT 1.0兼容的.

在样本输入上运行时,结果为:

<node id="DSN">
  <event id="2190">
    <attribute key="Teardown" />
    <attribute key="Resource" />
  </event>
</node>
Run Code Online (Sandbox Code Playgroud)

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

<element attr="   this    is an
                   attribute   " />
Run Code Online (Sandbox Code Playgroud)

将改为:

<element attr="this is an attribute" />
Run Code Online (Sandbox Code Playgroud)

如果您需要将空格保持在该值内,那么请参阅Gunther的答案.

  • -1 代表错误答案。问题是“仅”删除前导和尾随空白,而不是将封闭的空白标准化为单个空格。 (2认同)