首页 > 解决方案 > 如何在内联节点之间插入空格(并排)?

问题描述

我的问题很简单。我使用 php 将样式表应用于 XMLDocument。

我有一些这样的 XML 元素:

<a>
  Lorem
  <b>ipsum</b>
  <c>dolor<d>sit amet</d></c>
</a>

dolor和之间存在问题sit amet。我想知道Lorem ipsum dolor sit amet在每个文本节点之间使用空格打印的最简单方法。

我使用样式表的这一部分:

[...]
<xsl:value-of select="a/descendant-or-self::*" />
[...]

但结果是Lorem ipsum dolorsit amet

我也试过a/descendant-or-self::*a/descendant-or-self::*/text()用模板匹配文本()concat(' ', a/descendant-or-self::*),。

我不知道子元素的名称,这就是我使用的原因descendant-or-self::*

如何以正确的字间距将这些子元素打印为文本?

标签: xmlxslt

解决方案


我对您的问题的理解是,您只需要输出文本节点,丢弃元素,同时保持单词用空格分隔。如果是这样,你可以试试这个 XSL:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" indent="no"/>
    <xsl:template match="/">
        <xsl:variable name="out">
            <xsl:apply-templates/>
        </xsl:variable>
        <xsl:value-of select="normalize-space($out)"/>      
    </xsl:template>


    <xsl:template match="*[node()]">
            <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:value-of select="concat(' ',normalize-space(.))"/>
    </xsl:template>
</xsl:stylesheet>

该工作表只是递归地下降到任何节点,丢弃元素,提取文本并在它们前面加上一个空格。该normalize-space函数用一个空格替换一个或多个空格的序列。


推荐阅读