These days its rare to find any application not using XML for communicating with other applications. While we all use SAX or DOM parsers either directly or through JAX api, most of us are not aware of org.apache.xml.serialize.XMLSerializer class, which creates an xml string effortlessly. This supports both DOM and SAX. DOM serializing is done by calling serialize(Document) and SAX serializing is done by firing SAX events and using the serializer as document handler. Below is an example of converting a DOM object into xml string:
java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream(); org.apache.xml.serialize.OutputFormat outFormat = new org.apache.xml.serialize.OutputFormat(); org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer(); serializer.setOutputFormat(outFormat); serializer.setOutputByteStream(outStream); serializer.asDOMSerializer(); // document is the DOM object created elsewhere serializer.serialize(document.getDocumentElement()); String outMessage = outStream.toString();
No comments:
Post a Comment