如何处理从 XML 和 XSLT 文件生成的文本文件中的空格?
How to handle spaces in text file generated from a XML and XSLT file?
我一直在处理这个 XML 文件(超过 460.000 行),以便提取所有内容标签并将它们存储在单独的文本文件中。
此 XSLT 代码执行并创建了我想要的文件,但我不明白为什么生成的文本文件充满了白色 spaces,即使我使用 XSLT 文件中的 strip space 元素进行擦除所有的白色space都没有用。
这是我的 XML 文件:
<?xml version="1.0"?>
<sa>
<review>
<product>
<name>
Scary movie
</name>
</product>
<rating>
0.5
</rating>
<content>
bad
</content>
</review>
<review>
<product>
<name>
The Space
</name>
</product>
<rating>
0.5
</rating>
<content>
bad
</content>
</review>
</sa>
这是 XSLT 文件:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output method="text"/>
<xsl:template match="/*">
<xsl:for-each select="review">
<xsl:if test="rating=0.5">
<xsl:value-of select="ancestor-or-self::*/content"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
结果是:
bad
bad
为什么在 2 个 "content" 标签之间有这个 space?
xsl:strip-space 仅删除完全由白色组成的文本节点space。它不会 trim 节点中的前导和尾随白色 space 也包含可打印文本,例如:
<name>
The Space
</name>
为此,通常的方法是 normalize-space():
<xsl:value-of select="normalize-space(ancestor-or-self::*/content)"/>
或者不是在任何地方插入对 normalize space 的调用,您可能希望对具有身份模板规则和规则
的文档进行预处理传递
<xsl:template match="text()">
<xsl:value-of select="normalize-space()"/>
</xsl:template>
normalize-space() 可能做的比你想做的更多 - 它用单个 space 替换白色 space 的内部序列(包括换行符)。在 XSLT 2.0 中,很容易编写您自己的 trim() 函数来做一些不那么激进的事情。在 XSLT 1.0 中,这更难 - 它需要递归命名模板 - 所以这绝对是预处理过程的一部分。
我一直在处理这个 XML 文件(超过 460.000 行),以便提取所有内容标签并将它们存储在单独的文本文件中。 此 XSLT 代码执行并创建了我想要的文件,但我不明白为什么生成的文本文件充满了白色 spaces,即使我使用 XSLT 文件中的 strip space 元素进行擦除所有的白色space都没有用。
这是我的 XML 文件:
<?xml version="1.0"?>
<sa>
<review>
<product>
<name>
Scary movie
</name>
</product>
<rating>
0.5
</rating>
<content>
bad
</content>
</review>
<review>
<product>
<name>
The Space
</name>
</product>
<rating>
0.5
</rating>
<content>
bad
</content>
</review>
</sa>
这是 XSLT 文件:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output method="text"/>
<xsl:template match="/*">
<xsl:for-each select="review">
<xsl:if test="rating=0.5">
<xsl:value-of select="ancestor-or-self::*/content"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
结果是:
bad
bad
为什么在 2 个 "content" 标签之间有这个 space?
xsl:strip-space 仅删除完全由白色组成的文本节点space。它不会 trim 节点中的前导和尾随白色 space 也包含可打印文本,例如:
<name>
The Space
</name>
为此,通常的方法是 normalize-space():
<xsl:value-of select="normalize-space(ancestor-or-self::*/content)"/>
或者不是在任何地方插入对 normalize space 的调用,您可能希望对具有身份模板规则和规则
的文档进行预处理传递<xsl:template match="text()">
<xsl:value-of select="normalize-space()"/>
</xsl:template>
normalize-space() 可能做的比你想做的更多 - 它用单个 space 替换白色 space 的内部序列(包括换行符)。在 XSLT 2.0 中,很容易编写您自己的 trim() 函数来做一些不那么激进的事情。在 XSLT 1.0 中,这更难 - 它需要递归命名模板 - 所以这绝对是预处理过程的一部分。