我对XSLT和XPath还是比较陌生,并且在这个问题上已经碰壁了一段时间。

我有以下XML:

<reply>
    <multi-results>
        <multi-item>
            <name>node1</name>
            <information>
                <block>
                    <slot>A</slot>
                    <state>Online</state>
                    <colour>purple</colour>
                </block>
                <block>
                    <slot>B</slot>
                    <state>Online</state>
                    <colour>yellow</colour>
                </block>
                <block>
                    <slot>C</slot>
                    <state>Online</state>
                    <colour>red</colour>
                </block>
                <block>
                    <slot>D</slot>
                    <state>Online</state>
                    <colour>blue</colour>
                </block>
            </information>
        </multi-item>
    </multi-results>
    <address>
        <label>this is an arbitrary bit of text included for this example</label>
    </address>
</reply>


每个文件有可变数量的“块”条目。

我想“ CSV”数据,并且正在使用以下XSL:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="*/text()[normalize-space()]">
        <xsl:value-of select="normalize-space()"/>
    </xsl:template>
    <xsl:template match="*/text()[not(normalize-space())]" />
    <xsl:template match="block">
        <xsl:value-of select="slot"/>
        <xsl:text>|</xsl:text>
        <xsl:value-of select="state"/>
        <xsl:text>|</xsl:text>
        <xsl:value-of select="colour"/>
        <xsl:text>&#10;</xsl:text>
    </xsl:template>
</xsl:stylesheet>


输出:

node1A|Online|purple
B|Online|yellow
C|Online|red
D|Online|blue
this is an arbitrary bit of text included for this example


但是,输出同时包含“名称”和“标签” ...

我只想要我在XSL中明确要求的内容:

A|Online|purple
B|Online|yellow
C|Online|red
D|Online|blue


我不明白为什么。有人可以解释一下吗?

同样,可能有多个“名称”元素,每个元素都有自己数量的“块”元素。

提前谢谢了

最佳答案

<block>之外的元素正在使用默认模板规则进行处理。为了防止这种情况,您需要添加

<xsl:template match="/">
  <xsl:apply-templates select="block"/>
</xsl:template>


然后,您将不需要与文本节点匹配的模板规则,因为您无需将模板应用于文本节点。

关于xslt - XSL输出超出预期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8136421/

10-11 22:23
查看更多