package com.xml; import java.io.File; import java.io.StringWriter; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main { public static void main (String[] args) { try { //Create Document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); //Books Tag - Root Tag Element books = document.createElement("books"); document.appendChild(books); //Book Tag - Child Tag Element book1 = document.createElement("book"); books.appendChild(book1); Element name = document.createElement("name"); name.setTextContent("Head First EJB"); book1.appendChild(name); Element author = document.createElement("author"); author.setTextContent("Kathy Seira"); book1.appendChild(author); //Transform Document Object TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); //To write the dom object into a file StreamResult result = new StreamResult(new File("books.xml")); transformer.transform(source, result); //To write the dom object content into string StringWriter writer = new StringWriter(); StreamResult result1 = new StreamResult(writer); transformer.transform(source, result1); //System.out.println (writer.toString()); }catch (ParserConfigurationException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); }catch (TransformerConfigurationException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }
The output of the program
Head First EJB Kathy Seira