|
An example of how to create a basic XML document with DOM in Java.
Many of us programmers from time to time need to create an XML output of some kind. It sometimes is written to a file and simetimes printed to an HTTP response. In this article Java 5.0 and eclipse 3 has been used. When we quickly needs to test an application or function we can create the XML document “by hand”. Below is a snippet of Java code doing that. /** * Create XML style response message. * * @param responseCode * @param responseMessage * @return */ private String createResponse(int responseCode, String responseMessage) { StringBuffer resp = new StringBuffer("<hangup>"); resp.append("<responseCode>"); resp.append(responseCode); resp.append("</responseCode>"); resp.append("<responseMessage>"); resp.append(responseMessage); resp.append("</responseMessage>"); resp.append("</hangup>"); return resp.toString(); } After making the test application things need to become more serious, and the XML document need to be less hard coded and more flexible. In the following example the code will create an XML document that is like above, but now generated using DOM. public static final String RESPONSE_CODE = "responseCode"; public static final String RESPONSE_MESSAGE = "responseMessage"; /** * Create XML style response message and send it to the outputstream. * * @param out - OutputStream to send XML response via. * @param responseCode * @param responseMessage * @throws ParserConfigurationException * @throws TransformerConfigurationException * @throws TransformerException * @throws TransformerFactoryConfigurationError */ private void sendResponse(OutputStream out, int responseCode, String responseMessage) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError { org.w3c.dom.Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); //create the root element Element root = doc.createElement("hangup"); //all it to the xml tree doc.appendChild(root); Element childElement = doc.createElement(RESPONSE_CODE); childElement.setTextContent(String.valueOf(responseCode)); root.appendChild(childElement); childElement = doc.createElement(RESPONSE_MESSAGE); childElement.setTextContent(responseMessage); root.appendChild(childElement); // Use a Transformer for output StreamResult result = new StreamResult(out); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), result); } |