xsl:strip-space无法去除换行符

5
这是一个XML文件。"CategoryName"元素中的空格和换行符是有意的。
<?xml version="1.0" encoding="utf-8"?>
<group>
    <item>
        <id>item 1</id>
        <CategoryName>


        </CategoryName>
    </item>
    <item>
        <id>item 2</id>
        <CategoryName></CategoryName>
    </item>
    <item>
        <id>item 3</id>
        <CategoryName>      </CategoryName>
    </item>

</group>

以下是上述XML文件的XSLT文件。它的作用是清除“CategoryName”元素中的所有空格。然后,它将测试是否为空或非空“CategoryName”。
<?xml version="1.0" encoding="utf-8"?>
<!-- DWXMLSource="testempty.xml" -->

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" encoding="utf-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>

  <xsl:strip-space elements="*" /> <!--HERE IS STRIP SPACE-->


  <xsl:template match="/">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Untitled Document</title>
    </head>

    <body>
    <xsl:for-each select="/group/item">
      <xsl:if test="CategoryName = ''"> <!--HERE IS THE TEST-->
        <p>Empty</p>          <!--IT WILL OUTPUT 'EMPTY' IF THE ELEMENT IS EMPTY-->
      </xsl:if>
    </xsl:for-each>
    </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

问题在于,xsl:strip-space没有起到作用。只有第二个项目的“CategoryName”通过了“empty”测试。
问题出在哪里?

我在我的Eclipse上测试了这个,它按照你的期望工作。它打印了3个“Empty”。 - Weibo
我使用了Adobe Dreamweaver,它只显示一个空的。 - user1535147
可能是重复问题:https://dev59.com/a0jSa4cB1Zd3GeqPFXKE - user1693593
我之前看过那个问题,但它并没有解决我的问题。 - user1535147
2个回答

2
我不知道Dreamweaver正在使用哪个XSLT引擎,但这看起来是错误的。
我认为可能有一些XSLT处理器仅在您提供未解析的输入(词汇XML)时才应用xsl:strip-space,而不是如果您向它们提供DOM,则不会应用。规范中没有任何理由证明这种行为,但它使实现者的生活变得更加容易。
然而,值得指出的是,这不是xsl:strip-space预期使用的方式。它旨在用于删除“可忽略的”空格,即用于元素唯一内容缩进的空格。如果您正在使用XSLT 2.0模式感知转换,则这将被正式化为一个规则:xsl:strip-space不会影响具有简单内容的元素的内容。这是因为对于这样的元素剥离空格可能会使该元素违反模式。

同意!空格或回车终究不是空的! - Rookie Programmer Aravind
那么,我该如何测试空元素呢? - user1535147
使用测试 normalize-space(XX) != '' - Michael Kay

1

很明显,DeamWeaver的XSLT处理器有一个bug。

这里有另一种获得想要结果的方法:

替换为

   <xsl:if test="CategoryName = ''">

with:

   <xsl:if test="not(normalize-space(CategoryName))">

@user1535147,欢迎。我建议阅读一本关于XPath的好书——请参考这个答案获取好的资源:http://stackoverflow.com/a/341589/36305 - Dimitre Novatchev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接