How to copy particular element in an XML using XSLT 1.0

时间:2016-04-25 08:58:55

标签: xml xslt

First, let me provide the sample xml so you guys will be clear what am after.

<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. I need to neglect node c and d.

There is <xsl:copy> which can copy the elements, but I need to get particular element out of original XML.

Thank you.

1 个答案:

答案 0 :(得分:0)

确定您可以删除所需的元素。只需在身份转换后在指定元素上写空模板。

源XML

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

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>

输出XML

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

或者,选择要保留的特定节点:

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>