Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude attribute from a specific xml element using xslt

Tags:

xml

xslt

I am new in xslt. I have the following problem. I need within an xml, to remove a specific attribute (theAttributein the example) from a specific element (e.g. div). i.e.

<html>
   <head>...</head>
   <body>
      <div id="qaz" theAtribute="44">
      </div>
      <div id ="ddd" theAtribute="4">
         <div id= "ggg" theAtribute="9">
         </div>
      </div>
      <font theAttribute="foo" />
   </body>
</html>

to become

<html>
   <head>...</head>
   <body>
      <div id="qaz">
      </div>
      <div id ="ddd">
         <div id= "ggg">
         </div>
      </div>
      <font theAttribute="foo" />
   </body>
</html>

Where attribute theAtribute has been removed. I found this, http://www.biglist.com/lists/xsl-list/archives/200404/msg00668.html based on which i made attempts to find the proper solution.

i.e. <xsl:template match="@theAtribute" />

Which removed it from the whole document... and others like match, if choose, etc. Nothing worked.. :-( can you please help me on this? it sound trivial to me, but with xslt, i cannot cope at all...

Thank you all in advance

like image 449
Alexandros Avatar asked Jun 25 '10 07:06

Alexandros


2 Answers

What is not working? Do you want the same content, just without the @theAtribute?

If so, make sure your stylesheet has the empty template for @theAtribute, but also has an identity template that copies everything else into the output:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!--empty template suppresses this attribute-->
    <xsl:template match="@theAtribute" />
    <!--identity template copies everything forward by default-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

If you only want to suppress certain @theAtribute, then you can make the match criteria more specific. For instance, if you only wanted to remove that attribute from the div who's @id="qaz", then you could use this template:

<xsl:template match="@theAtribute[../@id='qaz']" />

or this template:

<xsl:template match="*[@id='qaz']/@theAtribute" />

If you want to remove @theAttribute from all div elements, then change the match expression to:

<xsl:template match="div/@theAtribute" />
like image 198
Mads Hansen Avatar answered Oct 13 '22 07:10

Mads Hansen


inside the select, you can exclude (or include,) the attribute, using the name function.

For example, <xsl:copy-of select="@*[name(.)!='theAtribute']|node()" />

like image 15
engineer Avatar answered Oct 13 '22 08:10

engineer