1

I have an XML file as shown below in which I need to replace a tag with another tag:

<?xml version="1.0" encoding='utf-8'?>

<result>

    <!-- some xml data along with lot of other tags -->

</result>

Now I want this XML to be like this: As you can see result tag is replaced with ClientHolder tag and everything else within result tag is same in ClientHolder tag as well.

<?xml version="1.0" encoding='utf-8'?>

<ClientHolder xmlns="http://www.host.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.host.com model.xsd">

    <!-- some xml data along with lot of other tags -->

</ClientHolder>

Here is my code so far and after that I am not able to understand how to use Document object to do above stuff:

String fileName = location + "/" + "client_" + clientId + ".xml";
File clientFile = new File(fileName);
Document doc = parseXML(clientFile);

// now how to use doc object?
john
  • 11,311
  • 40
  • 131
  • 251

1 Answers1

1

You can get all the nodes named as result and then modify them all, renaming the node and adding additional attributes:

NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);
    doc.renameNode(node, null, "ClientHolder");
    Element element = (Element) node;
    element.setAttribute("xmlns", "http://www.host.com");
    element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    element.setAttribute("xsi:schemaLocation", "http://www.host.com model.xsd");
}

Here is the imports:

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

And this is how you can save it to file:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(clientFile);
Source input = new DOMSource(doc);
transformer.transform(input, output);
Stanislav
  • 27,441
  • 9
  • 87
  • 82