Ondrej Sotolar
Ondrej Sotolar

Reputation: 1442

Replacing XML node via Java

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");  
}

Upvotes: 7

Views: 23545

Answers (2)

Venkat
Venkat

Reputation: 342

Easy way to do is using regular expression.

String payload= payload.replaceAll("<payload>([^<]*)</payload>", "<payload>NODATA</payload>");

This will make sure all the payload nodes contents are replaced with NODATA

Upvotes: -3

Vala
Vala

Reputation: 5674

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);
}

Upvotes: 12

Related Questions