Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Replace Node In XML

DZone's Guide to

Replace Node In XML

·
Free Resource
// replaces a node with a new (textual node)
// @Node node - the node (or Document) you want to replace.
// @nodeToReplace - the node you want to replace
// @replacementNode - the node you want to replace it with!


private static void replaceNodeWithString(Node node, Node nodeToReplace, Node replacementNode) {
	NodeList nodeList = node.getChildNodes();
	for(int i=0; i < nodeList.getLength(); i++){
		Node childNode = nodeList.item(i);
			 
		if(childNode.getNodeName().equals(nodeToReplace.getNodeName())){
			Element parentElement = (Element)childNode.getParentNode();
			parentElement.insertBefore(replacementNode, childNode);
			childNode.getParentNode().removeChild(childNode);
			parentElement.normalize();
			i--;
		}
		replaceNodeWithString(childNode, nodeToReplace, replacementNode);
	}
}
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}