首页 > 解决方案 > XSLT:修复了从所有区域输出文本的问题

问题描述

我有这个示例 Xml 文档

<root>
    <type1></type1>
    <type2>
        <text>
            This is a test
        </text>
    </type2>
    <type3>
        <child>3</child>
    </type3>
    <type4></type4>
    <type5></type5>
    <type6></type6>
    <type7>
        <text>
            This is a test
        </text>
        <child>7</child>
    </type7>
</root>

我希望最终的输出只包含来自 type3 和 type7 的数据

<root>
    <type3>
        <child>3</child>
    </type3>
    <type7>
        <text>
            This is a test
        </text>
        <child>7</child>
    </type7>
</root>

我正在使用 XSLT 来尝试生成上述输出

<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*" />  
<xsl:template match="root | type3 | type7 | *[ancestor::type3] | *[ancestor::type7] | comment() | processing-instruction() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
</xsl:template> 

</xsl:stylesheet>

但这会产生输出

<root>
   This is a test
   <type3>
       <child>3</child>
   </type3>
   <type7>
        <text> This is a test </text>
        <child>7</child>
   </type7>
</root>

如何阻止 xml 将文本保留在我不想保留的区域中,例如类型 2 节点?我知道这个问题是由于默认的内置模板造成的,但我不知道如何解决它。

标签: xmlxslt

解决方案


此 StackOverflow 帖子中给出了解决方案

解决方案是

<xsl:template match="root | node()[ancestor-or-self::type3] | node()[ancestor-or-self::type7] | comment() | processing-instruction() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
</xsl:template> 

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

推荐阅读