Search code examples
javadomstax

Adding DTD info to xml using DOM


I am using DOM to create an XML file and using StAX to parse another xml to get data selectively to write.

I am stuck at a point where I have the DTD event from Stax but i dont know how to write it to DOM document.

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

while (r.hasNext()) {
            int eventType = r.next();

            Node child;

            switch (eventType) {
            case XMLStreamConstants.CDATA:
                child = doc.createCDATASection(r.getText());
                break;
            case XMLStreamConstants.DTD:
            //??? - what shoould come here?
            break;

r is XMLEventReader object


Solution

  • Found the answer finally.

    Doctype is added when transforming the file.

     Transformer tFormer = 
      TransformerFactory.newInstance().newTransformer();
    //  Set system id
      tFormer.setOutputProperty(
      OutputKeys.DOCTYPE_SYSTEM, "systmId");
    
      Source source = new DOMSource(doc);
      Result result = new StreamResult(System.out);
      tFormer.transform(source, result);