在 XPath 中的树上使用 string() 时如何在节点之间添加空格

How to add spaces between nodes when using string() on a tree in XPath

我有一个 HTML 树,我在其中使用根上的 'string()' 查询从节点获取所有文本。

但是,我想在每个节点之间添加一个space。

string()'<root><div>abc</div><div>def</div></root>' 变为 'abcdef'

string() '<root><div>abc</div><div>def</div></root>' 应该 变成 'abc def '

您可以尝试使用 itertext() 方法,该方法遍历所有文本内容:

from lxml import etree

root = etree.XML('<root><div>abc</div><div>def</div></root>')
print(' '.join(e for e in root.itertext()))

它产生:

abc def

当 XML 比显示的更复杂或涉及混合内容时,不清楚您想要什么输出。在 XSLT 1.0 中,您必须对树进行递归下降,涉及类似

的内容
<xsl:template match="div">
  <xsl:if test="not(position()=1)"> </xsl:if>
  <xsl:value-of select="."/>
</xsl:template>

'<root><div>abc</div><div>def</div></root>' should become 'abc def '

在 XSLT 1.0 中,这将按以下方式完成:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/root">
    <xsl:for-each select="div">
        <xsl:value-of select="."/>
        <xsl:text> </xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

或者您可能想要检索所有文本节点,而不考虑文档结构。这可以通过以下方式完成:

<xsl:template match="/">
    <xsl:for-each select="//text()">
        <xsl:value-of select="."/>
        <xsl:text> </xsl:text>
    </xsl:for-each>
</xsl:template>