简体   繁体   English

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

[英]XSLT Remove leading and trailing whitespace of all attributes

How can I create an identical XML sheet, but with the leading and trailing whitespaces of each attribute removed? 如何创建相同的XML工作表,但删除了每个属性的前导和尾随空格? (using XSLT 2.0) (使用XSLT 2.0)

Go from this: 从这里开始:

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

To this: 对此:

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

I suppose I'd prefer to use the normalize-space() function, but whatever works. 我想我更喜欢使用normalize-space()函数,但无论如何都可以。

normalize-space() will not only remove leading and trailing whitespace, but it will also install a single space character in place of any sequence of consecutive whitespace characters. normalize-space()不仅会删除前导空格和尾随空格,还会安装一个空格字符来代替任何连续的空白字符序列。

A regular expression can be used to handle just leading and trailing whitespace: 正则表达式可用于处理前导和尾随空格:

<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>

This should do it: 这应该这样做:

<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>

This is also XSLT 1.0 compatible. 这也是XSLT 1.0兼容的。

When run on your sample input, the result is: 在样本输入上运行时,结果为:

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

One thing to note here is that normalize-space() will turn any whitespace within the attribute values into single spaces, so this: 这里需要注意的一点是, normalize-space()会将属性值中的任何空格转换为单个空格,因此:

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

Would be changed to this: 将改为:

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

If you need to keep whitespace within the value as-is, then please see Gunther's answer. 如果您需要将空格保持在该值内,那么请参阅Gunther的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM