سؤال

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

هل كانت مفيدة؟

المحلول

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());

    }

}

نصائح أخرى

A Document is also a Node – the root element is the first and only child of the document, and you can manipulate the child nodes of the Document like any other:

Document doc = parser.parse(new File("build.xml"));

Element newRoot = doc.createElement("newroot");
newRoot.appendChild(doc.getFirstChild());
doc.appendChild(newRoot);

// output to wrapped.xml
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(new File("wrapped.xml")));

This would also be fairly easy to do with StAX if you ever need to process files where the overhead of DOM parsing would be significant.

This may help

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class WriteXMLFile {

    public static void main(String argv[]) {

      try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("root");
        doc.appendChild(rootElement);



        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("build.xml"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

        System.out.println("File saved!");

      } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
      } catch (TransformerException tfe) {
        tfe.printStackTrace();
      }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top