PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to add doctype in XML document using DOM

 October 15, 2022     doctype, dom, java, xml     No comments   

Issue

I have created a XML document using DOM in Java. I am unable to add doctype. I want the doctype like this.

<!DOCTYPE IndInfo PUBLIC "EDAFileSomething" "EDAFileSomething_2_0.dtd">

Here is the document creation code.

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

Here is the Transformer object code.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
    transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException ex) {
    Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}
DOMSource source = new DOMSource(doc);
try {

    StreamResult result = new StreamResult(System.out);
    transformer.transform(source, result);
} catch (TransformerException ex) {
    Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}

System.out.println("File saved!");

Solution

You can construct the doctype with the DOM and set the doctype as an output property.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
DOMImplementation domImpl = document.getImplementation();
DocumentType doctype = domImpl.createDocumentType("doctype",
    "-//Oberon//YOUR PUBLIC DOCTYPE//EN",
    "YOURDTD.dtd");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(database));
transformer.transform(source, result);


Answered By - Adam
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing