grobartn grobartn - 3 months ago 7x
Java Question

Add an element around root element of given XML file that is stored in org.w3c.dom.Document

So i am trying to do this. Add new root element and wrap old one in it.

Given this as starting condition

// this part uses SAXParser = xmlSrc.parse(is); // *is* is InputStream

The initial condition is not really negotiable but I am open to hear comments there too

So given this xml file

<?xml version="1.0" encoding="UTF-8"?>

I need in Java to generate an InputStream that will contain xml file in it of this format

<?xml version="1.0" encoding="UTF-8"?>

Stored in some InputStream isNewXML

I am curious what is the best way to go about doing this.
I am new to Java and java has billion ways to do the same thing so out in dark which would be the best

jt. jt.

Using your example input, this creates the requested output. Ideally, you would handle exceptions and close inputstreams, output streams, and writers properly:


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

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

public class XmlTest

    public static void main(String[] args) throws Exception
        InputStream is = new FileInputStream("test.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document oldDoc = builder.parse(is);
        Node oldRoot = oldDoc.getDocumentElement();
        Document newDoc = builder.newDocument();
        Element newRoot = newDoc.createElement("newroot");
        newRoot.appendChild(newDoc.importNode(oldRoot, true));

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(newDoc);
        Writer writer = new OutputStreamWriter(out);
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);

        InputStream isNewXML = new ByteArrayInputStream(out.toByteArray());