import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.DOMImplementation; import org.apache.xerces.dom.DocumentTypeImpl; public class CreateXMLdocDOM1 { public static void main(String[] args) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); DOMImplementation domImplementation = docBuilder.getDOMImplementation(); DocumentTypeImpl documentType = (DocumentTypeImpl)domImplementation.createDocumentType("root", null, "sample.dtd"); Document document = domImplementation.createDocument(null, null, documentType); Element root = document.createElement("root"); Element a = document.createElement("a"); root.appendChild(a); EntityReference x = document.createEntityReference("x"); a.appendChild(x); a.appendChild(document.createTextNode(" world")); document.appendChild(root); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); LSOutput output = impl.createLSOutput(); output.setByteStream(System.out); writer.write(document, output); } catch(ParserConfigurationException ex) { ex.printStackTrace(); } catch(ClassNotFoundException ex) { ex.printStackTrace(); } catch(InstantiationException ex) { ex.printStackTrace(); } catch(IllegalAccessException ex) { ex.printStackTrace(); } } }