Search code examples
javaxmlxml-parsingsaxparserdomparser

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
org.w3c.com.Document = 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"?>
<root1>
   <elem>...</elem>
</root1>

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"?>
<newroot>
   <root1>
       <elem>...</elem>
   </root1>
</newroot>

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


Solution

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

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    
    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 javax.xml.transform.stream.StreamResult;
    
    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");
            newDoc.appendChild(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);
            writer.flush();
    
            InputStream isNewXML = new ByteArrayInputStream(out.toByteArray());
    
        }
    
    }