Share on Google+Share on Google+

Example of getDocType method in DOM API.

In this section, you will see the example of getDocType method of dom api.

getDocType() Example in DOM API

In this section, we will discuss about the implementation of the getDocType() method. This method checks that DTD(Document Type Definition) is provided or not in the XML document. Validating a XML file needs a xml file and its DTD document.

First of all construct a well-formed xml file along with a DTD file. This DTD file defines all elements to keep in the xml file. A DTD defines the document structure with a list of legal elements and attributes.

Description of program:

In this program, first we parse the xml file using parse() method and create a DOM Tree. Invoke the object of document class and call the getDocType().

Then check for DTD as if ( docType == null ).

if the condition is true then no DTD is found otherwise found.


<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE order SYSTEM "order.dtd ">                


<!ELEMENT orders (name,price,qty )>
<!ELEMENT price (#PCDATA)>

 import javax.xml.parsers.*; 
 import org.w3c.dom.*;  
 class ExampleGetDocType 
 public static void main String args [  ]  )  
 try  {  
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (  ) 
 DocumentBuilder db=factory.newDocumentBuilder (  ) 
 Document doc=db.parse "order.xml" 
 DocumentType docType = doc.getDoctype (  ) 
 if  docType == null 
         System.out.println " no DTD provided" 
         System.out.println " DTD provided" 
      }  catch Exception ce )  
   System.out.println ce.getMessage (  )  ) ;



C:\>java ExampleGetDocType

      DTD provided

Download The Example:



Posted on: September 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null