简体   繁体   English

如何使用XSLT 1.0复制XML中的特定元素

[英]How to copy particular element in an XML using XSLT 1.0

First, let me provide the sample xml so you guys will be clear what am after. 首先,让我提供示例xml,以便大家清楚接下来的内容。

<a>1</a>
<b>1</b>
<c>1</c>
<d>1</d>
<e>1</e>
<f>1</f>

Is is possible to copy node from a to b and from e to f. 可以将节点从a复制到b,从e复制到f。 I need to neglect node c and d. 我需要忽略节点c和d。

There is <xsl:copy> which can copy the elements, but I need to get particular element out of original XML. <xsl:copy>可以复制元素,但是我需要从原始XML中获取特定的元素。

Thank you. 谢谢。

Sure you can remove needed elements. 当然,您可以删除所需的元素。 Simply write empty templates on specified elements after an identity transform. 身份转换后,只需在指定的元素上写空模板即可。

Source XML 源XML

<root>
   <a>1</a>
   <b>1</b>
   <c>1</c>
   <d>1</d>
   <e>1</e>
   <f>1</f>
</root>

XSLT 1.0 XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>

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

  <!-- Empty Template to Remove Elements -->   
  <xsl:template match="c|d"/>

</xsl:stylesheet>

Output XML 输出XML

<root>
   <a>1</a>
   <b>1</b>
   <e>1</e>
   <f>1</f>
</root>

Alternatively, select particular nodes to keep: 或者,选择要保留的特定节点:

XSLT 1.0 XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>

  <!-- Root Template Match -->    
  <xsl:template match="root">
    <xsl:copy>
      <xsl:apply-templates select="a|b|e|f"/>
    </xsl:copy>
  </xsl:template>

  <!-- Select Particular Elements -->   
  <xsl:template match="a|b|e|f">
      <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM