【问题标题】:xsl:copy-of. Retain original parent node?xsl:副本。保留原来的父节点?
【发布时间】:2021-12-28 13:26:36
【问题描述】:

我见过很多xsl:copy-of 示例,例如这个,其中包含的父节点是硬编码的。即<output> 但有没有办法使用xsl:copy-of 并保留父节点? <library> 在这种情况下。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <category name="dogs">
        <book>
            <name>All about dogs</name>
            <author>Someone</author>
        </book>
    </category>
     <category name="cats">
        <book>
            <name>All about cats</name>
            <author>Someone</author>
        </book>
    </category>
</library>

XSL:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <output>
            <xsl:copy-of select="library/category[@name='cats']" />
        </output>
    </xsl:template>
</xsl:stylesheet>

当前输出:

<?xml version="1.0" encoding="UTF-8"?>
    <output>
        <category name="cats">
            <book>
                <name>All about cats</name>
                <author>Someone</author>
            </book>
        </category>
    </output>

【问题讨论】:

  • 在 XSLT 3 中,您可以使用 &lt;xsl:copy-of select="snapshot(library/category[@name='cats'])/.."/&gt;
  • 你能发布一个期望输出的例子吗?

标签: xslt-2.0 xpath-2.0


【解决方案1】:

不,xsl:copy-of 执行所选节点的深层复制。如果要发出节点的父节点,则需要以不同的方式处理内容。

一种方法是应用模板并拥有一个匹配有猫的元素的模板,使用xsl:copy 作为library 元素,然后xsl:copy-of 选择带有猫的category,以及更通用的模板匹配其他仅继续处理且不生成任何内容的节点:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    
    <xsl:template match="/">
        <output>
          <xsl:apply-templates />
        </output>
    </xsl:template>
    
    <xsl:template match="*[category[@name='cats']]">
        <xsl:copy>
            <xsl:copy-of select="category[@name='cats']" />
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="node()">
        <xsl:apply-templates/>
    </xsl:template>
    
</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多