我可以使用 xslt 让父节点与子节点一起复制吗?

Can I get the parent nodes to copy with the child node using xslt?

我正在尝试包括我正在复制的节点的父节点。

这是示例文件:

    <A>
       <B>
          <C1>Text Value</C1> 
          <C2></C2>
          <C3></C3>
          <C4></C4>
      </B>
   </A>

我希望输出为:

 <A>
    <B>
       <C1>Text Value</C1>
    </B>
</A>

这是我的 xslt:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>
  
  
 <xsl:template match="/A/B/C1">
  <xsl:copy>
   <xsl:apply-templates select="/A/B/C1"/>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

但是,我的输出没有显示父节点。

编辑: C1 将始终具有相同的 Xpath。我还想包括节点的文本。

这是生成您显示的结果的一种方法:

XSLT 1.0

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

<xsl:template match="*">
    <xsl:copy>
        <xsl:apply-templates select="*[descendant-or-self::C1] | C1/text()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Edit: C1 will always have the same Xpath.

嗯,还有一个:

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

<xsl:template match="/">
    <A>
        <B>
            <xsl:copy-of select="A/B/C1"/>    
        </B>
    </A>
</xsl:template>

</xsl:stylesheet>