I have to build an XML document from pieces of existing ones, and then output it as a string. What libraries should I use?
Pramod Hirole If you have pieces of existing valid documents as nodes then you can import those into the document you want to build by appending those nodes as child elements to the document.
The following code will do this:
document.importNode(doc1Elm); document.importNode(doc2Elm); document.appendchild(doc1Elm); docElm1.appendChild(docElm2);To write document object as a string you need to serialize it. You can use the Apache Xerces parser available from Apache. You should use XMLSerializer class to serialise document as String. Here is code sniplet.
// import following package import org.apache.xml.serialize.*; // following code serializes // document to domstr String OutputFormat of = new OutputFormat("XML","UTF-8",true); XMLSerializer serializer = new XMLSerializer(); ByteArrayOutputStream baos = new ByteArrayOutputstream() serializer.setOutputFormat(of); serializer.setOutputstream(baos); serializer.serialize(document); String domstr = new String(baos.toByteArray()) // domstr contains document as a String