首页 > 解决方案 > XSLT:复制子元素与属性匹配的元素

问题描述

很明显,这个问题的一个变体以前已经被问过很多次了。我已经筛选了许多其他问题,但似乎仍然找不到答案。

给定一个如下所示的 XML 文档:

<Media Attribute="4">
  <Printed SomeAttribute="3">
    <Book ID="1" OtherAttribute="2">
      <Author ID="A">Author Name1</Author>
      <Title>Some Title</Title>
    </Book>
    <Book ID="2" OtherAttribute="2">
      <Author ID="A">Author Name2</Author>
      <Title>Another Book Name</Title>
    </Book>
  </Printed>
</Media>

我正在寻找@ID="1"使输出看起来如下所示的书:

<Media Attribute="4">
  <Printed SomeAttribute="3">
    <Book ID="1" OtherAttribute="2">
      <Author ID="A">Author Name1</Author>
      <Title>Some Title</Title>
    </Book>
  </Printed>
</Media>

我尝试了以下不同的变体,但它不起作用:

<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="Media">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/Media/Printed/Book[@ID='1']]">
  <xsl:copy>
    <xsl:copy-of select="@*" />
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

我可以成功复制根节点,并且可以Book使用递归成功复制元素copy-of,但我不确定如何以Media/Printed非递归方式匹配/选择父节点(),同时还使用Book递归复制元素。

非常感谢!

标签: xsltxpath

解决方案


如何以Media/Printed非递归方式匹配/选择父节点()

为什么不一直递归地做:

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="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Printed">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="Book[@ID='1']"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

或者,您可以这样做:

<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="/Media">
    <xsl:copy>
        <xsl:copy-of select="@*"/>
        <Printed>
            <xsl:copy-of select="Printed/@*"/>
            <xsl:copy-of select="Printed/Book[@ID='1']"/>
        </Printed>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

推荐阅读