java - Added a Document to New Root Element -


i have below document want add document under in tag.

current document

<order> </order> 

expecting document

<newdoc>     <order>     </order> </newdoc> 

i have tried below code (without luck):

ordernewdoc.appendchild(orderolddoc); 

any appreciated.

a simple way of doing through dom follows

/**  * created rgovind on 11/10/2016.  */ import java.io.bytearrayinputstream; import java.io.inputstream; import java.io.outputstreamwriter; import java.io.writer; import java.nio.charset.standardcharsets;  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 xmlrootadd {     public static void main(string[] args) throws exception     {         string xml = "<order></order>";         inputstream istream =  new bytearrayinputstream(xml.getbytes(standardcharsets.utf_8));          documentbuilderfactory factory = documentbuilderfactory.newinstance();         documentbuilder builder = factory.newdocumentbuilder();          document orderdoc = builder.parse(istream);         node oldordernode = orderdoc.getdocumentelement();         document newdocument = builder.newdocument();         element newroot = newdocument.createelement("newdoc");         newdocument.appendchild(newroot);         newroot.appendchild(newdocument.importnode(oldordernode, true));          /*print , test*/         domsource domsource = new domsource(newdocument);         writer writer = new outputstreamwriter(system.out);         streamresult result = new streamresult(writer);         transformerfactory tf = transformerfactory.newinstance();         transformer transformer = tf.newtransformer();         transformer.transform(domsource, result);         writer.flush();      } } 

prints :

<?xml version="1.0" encoding="utf-8" standalone="no"?><newdoc><order/></newdoc> 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -