Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename XML node name

Tags:

java

xml

I want to rename the existing XML node into new name. I am doing XML parsing using DOM concept java, i have set of node which contains same name. for example

<names> 
    <abc>Apple</abc> 
    <abc>Ball</abc>
    <abc>Cat</abc> 
    <abc>Doll</abc> 
    <abc>Elephant</abc> 
    </names>

I the above example there is set of nodes contains value. in that example i want to change the node value (ie)

<names> 
    <name>Apple</name> 
    <name>Ball</name>
    <name>Cat</name> 
    <name>Doll</name> 
    <name>Elephant</name> 
    </names>

is this possible to do in DOM, i am pretty much new to parsing concept using DOM.. Thanks for valuable comments.

like image 284
RAAAAM Avatar asked Jun 30 '11 07:06

RAAAAM


1 Answers

Similar to my answer in updating a property of a xml tag :

public void changeTagName(Document doc, String tag, String fromTag, String toTag) {
    NodeList nodes = doc.getElementsByTagName(fromTag);
    for (int i = 0; i < nodes.getLength(); i++) {
        if (nodes.item(i) instanceof Element) {
            Element elem = (Element)nodes.item(i);
            doc.renameNode(elem, elem.getNamespaceURI(), toTag);
        }
    }
}
like image 128
Ron Avatar answered Sep 22 '22 13:09

Ron