Olli
Olli

Reputation: 89

Add Attribute to all child Elements using apply-templates

I try to add an attribute web to all child elements of the element web by using apply-template.

source xml

<p></p>
<tabel>
 <tr>
  <td>
   <web>
    <p></p>
    <p></p>
   </web>
  </td>
 </tr>
 <tr>
  <td>
   <web>
    <p></p>
    <ul>
     <li></li>
     <li></li>
    </ul> 
   </web>
  </td>
 </tr>
</tabel>

target xml

<p></p>
<tabel>
 <tr>
  <td>
   <p class="web"></p>
   <p class="web"></p>
  </td>
 </tr>
 <tr>
  <td>
   <p class="web"></p>
   <ul class="web">
    <li></li>
    <li></li>
   </ul> 
  </td>
 </tr>
</tabel>

my xsl

<xsl:template match="p">
 <p>
  <xsl:apply-templates/>
 </p>
</xsl:template>   
<xsl:template match="web">
 <xsl:apply-templates/>
</xsl:template>   
<xsl:template match="ul">
 <ul>
  <xsl:apply-templates/> 
 </ul>
</xsl:template>

Is there any possibility to apply-templates and add the attribute web to all child elements of web? Does anyone have an idea, how to do this?

Upvotes: 0

Views: 959

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116993

Given a well-formed input such as:

XML

<html>
    <p></p>
    <tabel>
      <tr>
        <td>
        <web>
          <p></p>
          <p></p>
        </web>
        </td>
      </tr>
      <tr>
        <td>
        <web>
          <p></p>
            <ul>
              <li></li>
              <li></li>
            </ul> 
        </web>
        </td>
      </tr>
    </tabel>
</html>

the following stylesheet:

XSLT 1.0

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

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

<xsl:template match="web">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="web/*">
    <xsl:copy>
        <xsl:attribute name="class">web</xsl:attribute>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

will return:

<html>
   <p></p>
   <tabel>
      <tr>
         <td>
            <p class="web"></p>
            <p class="web"></p>
         </td>
      </tr>
      <tr>
         <td>
            <p class="web"></p>
            <ul class="web">
               <li></li>
               <li></li>
            </ul>
         </td>
      </tr>
   </tabel>
</html>

Note that tabel is not a valid HTML element.

Upvotes: 1

Related Questions