为什么文本节点出现在转换后的 xml 中

2024-02-29

我想使用 xslt 从 xml 文件的元素中选择一些具有特定值的节点集。我确实得到了我想要的节点,但我也从文本节点得到了一些序列化文本。 你能帮我去掉这段文字吗?

这是源文件:

<surveys>
<survey id='01'>
    <category>cat1</category>
    <questions>
        <question id='1'>Y</question>
        <question id='2'>Y</question>
        <question id='3'>Y</question>
        <question id='4'>Y</question>
    </questions>
</survey>
<survey id='02'>
    <category>cat2</category>
    <questions>
        <question id='1'>Y</question>
        <question id='2'>Y</question>
        <question id='3'>N</question>
        <question id='4'>N</question>
    </questions>
</survey>
<survey id='03'>
    <category>cat1</category>
    <questions>
        <question id='1'>N</question>
        <question id='2'>N</question>
        <question id='3'>N</question>
        <question id='4'>N</question>
    </questions>
</survey>
<survey id='04'>
    <category>cat3</category>
    <questions>
        <question id='1'>N</question>
        <question id='2'>N</question>
        <question id='3'>Y</question>
        <question id='4'>Y</question>
    </questions>
</survey>
</surveys>

这是转换文件:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="/">
    <surveys>
        <category/>
        <xsl:apply-templates/>
    </surveys>
</xsl:template>

<xsl:template match="survey[category = 'cat2']">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

结果是这样的:

<surveys>cat1YYYY<survey id="02">
    <category>cat2</category>
    <questions>
        <question id="1">Y</question>
        <question id="2">Y</question>
        <question id="3">N</question>
        <question id="4">N</question>
    </questions>
</survey>cat1NNNNcat3NNYY</surveys>

因此,我想删除调查元素后第一行中的“cat1YYYY”和调查元素后最后一行中的“cat1NNNNcat3NNYY”。 我想了解为什么它在那里;-)


我想了解为什么它在那里

它之所以存在,是因为您不加区别地应用模板 - 而 XSLT 有一些内置模板规则 https://www.w3.org/TR/xslt/#built-in-rule复制文本节点作为默认值。

为了防止这种情况发生,您可以添加自己的模板来覆盖默认行为:

<xsl:template match="text()" />

或者 - 最好 - 有选择地应用模板以开始:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="/surveys">
    <surveys>
        <category/>
        <xsl:apply-templates select="survey[category = 'cat2']"/>
    </surveys>
</xsl:template>

<xsl:template match="survey">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

顺便说一句,可以缩短为:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="/surveys">
    <surveys>
        <category/>
        <xsl:copy-of select="survey[category = 'cat2']"/>
    </surveys>
</xsl:template>

</xsl:stylesheet>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么文本节点出现在转换后的 xml 中 的相关文章

随机推荐