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?
2

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.