XSLT规范化空间不起作用



这是我的输入xml

<?xml version="1.0" encoding="utf-8"?>
<content>
  <body>
        <p>This      is a Test</p>
        <p>
          Toronto,           ON - Text added here.
        </p>
  </body>
</content>

这是我的样式表

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  xmlns:str="http://exslt.org/strings"
  extension-element-prefixes="str">
  <xsl:output method="xml" indent="no" />

  <!-- Root / document element-->
  <xsl:template match="/">
    <xsl:apply-templates select="node()"/>
  </xsl:template>
  <xsl:template match="*/text()">
    <xsl:value-of select="normalize-space()"/>
  </xsl:template>
</xsl:stylesheet>

当我使用ASP。NET XslCompiledTransform的transform方法,并在浏览器中查看结果,我仍然可以看到空间,规范化空间似乎不起作用。

有人能告诉我我做错了什么吗

非常感谢!

此转换

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[not(text()[2])]/text()">
    <xsl:value-of select="normalize-space()"/>
  </xsl:template>
</xsl:stylesheet>

应用于提供的源XML文档时

<content>
  <body>
        <p>This      is a Test</p>
        <p>
          Toronto,           ON - Text added here.
        </p>
  </body>
</content>

生成所需的正确结果

<content><body><p>This is a Test</p>
        <p>Toronto, ON - Text added here.</p>
  </body>
</content>

更新

如果问题是由类似空格的字符引起的,这里有一个解决方案,可以用空格替换不需要的字符(每个文本节点最多40个),然后normalize-space()就可以完成它的工作:

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:variable name="vAllowed" select=
   "concat('ABCDEFGHIJKLMNOPQRSTUVWXUZ', 'abcdefghijklmnopqrstuvwxyz',
           '0123456789.,-')"/>
  <xsl:variable name="vSpaces" select="'                                        '"/>
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[not(text()[2])]/text()">
    <xsl:value-of select=
    "normalize-space(translate(., translate(.,$vAllowed,''), $vSpaces))"/>
  </xsl:template>
</xsl:stylesheet>

当转换应用于此源XML文档时

<content>
  <body>
        <p>This \     is a  ~~~ Test</p>
        <p>
          Toronto,    ```       ON - Text added here.
        </p>
  </body>

生成所需的正确结果

<content>
  <body>
        <p>This is a Test</p>
        <p>Toronto, ON - Text added here.</p>
  </body>
</content>
Dimitre的答案当然很棒,但有一个拼写错误。在$vAllowed中,他缺少一个大写的"Y"

同样出于我自己的目的,我需要一个引号或撇号作为允许的字符。我把它添加到变量中,如下所示:

<xsl:variable name="vAllowed" select=
    "concat('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz',
    '0123456789.,-', '&apos;&apos;')"/>

相关内容

最新更新