2

The sample xml file is shown below

<a>
<apple color="red"/>
</a>

What should I write in XSLT so that i can get the sample output below ?

<AAA>
<BB bbb="#apple"/> <!-- if possible make it auto close -->
</AAA>
2
  • i not sure how to extract it, was thinking about to hard code it eg: <AAA> <BB> **hard code here** </BB> <AAA> Commented Dec 19, 2011 at 17:08
  • You may want to have a look at a more generic, completely parameterized solution. :) Commented Dec 19, 2011 at 17:53

2 Answers 2

2

Here is a generic solution, that accept the name replacements to be made as parameters:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pReps">
  <e oldName="a" newName="AAA"/>
  <e oldName="apple" newName="BB"/>
  <a oldName="color" newName="bbb"/>
 </xsl:param>

 <xsl:variable name="vReps" select=
     "document('')/*/xsl:param[@name='pReps']"/>

 <xsl:template match="*">
     <xsl:element name=
     "{$vReps/e[@oldName = name(current())]/@newName}">
      <xsl:apply-templates select="@*|node()"/>
     </xsl:element>
 </xsl:template>

 <xsl:template match="@*">
  <xsl:attribute name=
  "{$vReps/a[@oldName = name(current())]/@newName}">
   <xsl:value-of select="concat('#', name(..))"/>
  </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<a>
    <apple color="red"/>
</a>

the wanted, correct result is produced:

<AAA>
   <BB bbb="#apple"/>
</AAA>
Sign up to request clarification or add additional context in comments.

Comments

1

Use name() or local-name() functions:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

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

  <xsl:template match="*">
    <BB bbb="{concat('#', name())}"/>
  </xsl:template>

</xsl:stylesheet>

2 Comments

thanks it works perfectly ~ just because of the {name()} function ~ thanks a lot
@KirillPolishchuk: The result of your transformation is different from the OP's wanted result. Please, check and correct. Also, I believe that my generic solution might be interesting to have a look at, as it is completely parameterized vs the hardcoded values in this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.