goshanoob
goshanoob

Reputation: 75

How to wrap node with certain attribute?

I have in-document with XML code:

<root>
 <a id="att_1">
  <a id="att_2"/>
  <a id="att_3">
   <a id="att_4"> 
    <a id="att_5"/>
   </a>
   <a id="att_6"/>
  </a>
 </a>
</root>

I need out-document, where node with id="att_6" is wraped in b node:

<root>
 <a id="att_1">
  <a id="att_2"/>
  <a id="att_3">
   <a id="att_4"> 
    <a id="att_5"/>
   </a>
   <b>
    <a id="att_6"/>
   </b>
  </a>
 </a>
</root>

I try copy all nodes from in-document into out-doc firstly. Secondly I need to wrap one node with certain id. This is my stylesheet:

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

  <xsl:template match="a">
    <b>
      <xsl:copy>
        <xsl:apply-templates select=".[@id = 'att_6']"/>
      </xsl:copy>
    </b>
  </xsl:template>

How can I do it?

Upvotes: 1

Views: 79

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

You're on the right track:

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

<xsl:template match="a[@id='att_6']">
    <b>
        <xsl:copy-of select="."/>
    </b>
</xsl:template>     

You just need to match the node(s) you want to wrap and handle them as shown above. xsl:copy-of does a deep copy of the context node and all its contained nodes.

Everything else is handled by the identity transform.

Upvotes: 1

Related Questions