3

I want to replace below node

 <Test>
        <Test.1>1</Test.1>
        <Test.2>ABC</Test.2>
        <Test.3>XXX</Test.3>
   </Test>

So If my input XML has Test node then "Test" node-name should be replace with node name as "aaa" Output should be like:

<aaa>
            <aaa.1>1</aaa.1>
            <aaa.2>ABC</aaa.2>
            <aaa.3>XXX</aaa.3>
 </aaa>

I have tried like:

 <xsl:when test="../name()='Test'">
     <aaa>
        <aaa.1>1</aaa.1>
        <aaa.2>ABC</aaa.2>
        <aaa.3>XXX</aaa.3>             
     </aaa>       

   </xsl:when>
0

2 Answers 2

3

You could use substring-after() to get the rest of the name and create the new one...

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

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

  <xsl:template match="*[starts-with(local-name(),'Test')]">
    <xsl:element name="aaa{substring-after(local-name(),'Test')}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

Comments

0

As I see, you want to change node name starting with Test, replacing Test with aaa.

To perform this task you need a template matching elements, which names start with Test. It can be made using a predicate in match attribute:

match="*[starts-with(name(), 'Test')]"

The content of this template should include:

  • Create a new element, with changed name (aaa + the "rest" of the tag name).
  • Apply templates to the content of the current element, like in the identity template.
  • Close the just created element.

Of course, the script should include also the identity template.

So the whole script can look like below:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes" />
  <xsl:strip-space elements="*"/>

  <xsl:template match="*[starts-with(name(), 'Test')]">
    <xsl:element name="aaa{substring(name(), 5)}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>

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

Comments

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.