user3409289
user3409289

Reputation:

How to reverse a xml nodes with their data in java

Hi I am working with XML in java and my XML looks like

<Name>
<firstName>FName</firstName>
<lastName>LName</lastName>
</Name>

I want to convert this XML in to the below format.

<Name>
<FName>firstName</FName>
<LName>lastName</LName>
</Name>

I am looking for some API or method which will convert this in one shot. I mean converting Tags in to value and value into Tags.

Upvotes: 0

Views: 415

Answers (1)

Syam S
Syam S

Reputation: 8499

You can use xslt for this. The following xsl swaps all leaf node name and value.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="/*">
        <xsl:element name="{name()}">
            <xsl:copy-of select="@*|b/@*" />
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="*[*][parent::*]">
        <xsl:element name="{name()}">
            <xsl:copy-of select="@*|b/@*" />
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="*[not(*)]">
        <xsl:element name="{.}">
            <xsl:copy-of select="@*|b/@*" />
            <xsl:value-of select="name()"></xsl:value-of>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

Sampel program

import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Test {

    public static void main(String[] args) throws Exception {
        TransformerFactory factory = TransformerFactory.newInstance();
    Source xslt = new StreamSource(new File("transform.xslt"));
    Transformer transformer = factory.newTransformer(xslt);

    Source text = new StreamSource(new File("data.xml"));
    transformer.transform(text, new StreamResult(new File("output.xml")));
    System.out.println("Done");
    }

}

Output :

<?xml version="1.0" encoding="UTF-8"?>
<Name>
    <FName>firstName</FName>
    <LName>lastName</LName>
</Name>

Upvotes: 1

Related Questions