Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing XML node via Java

Tags:

java

xml

I wan to replace a node in XML document with another and as a consequence replace all it's children with other content. Following code should work, but for an unknown reason it doesn't.

File xmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();

NodeList nodes = doc.getElementsByTagName("NodeToReplace");
for (int i = 0; i < nodes.getLength(); i++) {

    NodeList children = nodes.item(i).getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
          nodes.item(i).removeChild(children.item(j));
    }
        doc.renameNode(nodes.item(i), null, "MyCustomTag");  
}

EDIT-

After debugging it for a while, I sovled it. The problem was in moving index of the children array elmts. Here's the code:

NodeList nodes = doc.getElementsByTagName("NodeToReplace");
for (int i = 0; i < nodes.getLength(); i++) {

    NodeList children = nodes.item(i).getChildNodes();

    int len = children.getLength();
    for (int j = len-1; j >= 0; j--) {
        nodes.item(i).removeChild((Node) children.item(j));
    }
    doc.renameNode(nodes.item(i), null, "MyCustomTag");  
}
like image 421
Ondrej Sotolar Avatar asked Oct 26 '11 14:10

Ondrej Sotolar


People also ask

Which method is used to replace nodes?

The replaceChild() method is used to replace a node.

Is XML compatible with Java?

JAVA provides excellent support and a rich set of libraries to parse, modify or inquire XML documents.

How do you remove a node from a file in Java?

Remove a Text Node Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.


1 Answers

Try using replaceChild to do the whole hierarchy at once:

NodeList nodes = doc.getElementsByTagName("NodeToReplace");
for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);
    Node newNode = // Create your new node here.
    node.getParentNode().replaceChild(newNode, node);
}
like image 100
Thor84no Avatar answered Oct 03 '22 19:10

Thor84no