Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: How to change the parent tag name and Delete an attribute from XML file?

Tags:

xslt

I have an XML file from which I need to delete an attribute with name "Id" (It must be deleted wherever it appears) and also I need to rename the parent tag, while keeping its attributes and child elements unaltered .. Can you please help me modifying the code. At a time, am able to achieve only one of the two requirements .. I mean I can delete that attribute completely from the document or I can change the parent tag .. Here is my code to which removes attribute "Id":

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

Please help me changing the parent tag name from "Root" to "Batch".

like image 459
InfantPro'Aravind' Avatar asked Nov 20 '09 10:11

InfantPro'Aravind'


2 Answers

None of the offered solutions really solves the problem: they simply rename an element named "Root" (or even just the top element), without verifying that this element has an "Id" attribute.

wwerner is closest to a correct solution, but renames the parent of the parent.

Here is a solution that has the following properties:

  • It is correct.
  • It is short.
  • It is generalized (the replacement name is contained in a variable).

Here is the code:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:variable name="vRep" select="'Batch'"/>

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

  <xsl:template match="@Id"/>

  <xsl:template match="*[@Id]">
    <xsl:element name="{$vRep}">
      <xsl:apply-templates select="node()|@*"/>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>
like image 62
Dimitre Novatchev Avatar answered Oct 14 '22 10:10

Dimitre Novatchev


<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()|text()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="@Id" />
<xsl:template match="Root">
  <Batch>
    <xsl:copy-of select="@*|*|text()" />
  </Batch>
</xsl:template>
like image 28
Erlock Avatar answered Oct 14 '22 10:10

Erlock