Home Tutorial Xml Dom Example of getDocType method in DOM API.

 
 

Share on Google+Share on Google+
Example of getDocType method in DOM API.
Posted on: September 23, 2010 at 12:00 AM
Advertisement
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.

order.xml

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE order SYSTEM "order.dtd ">                
<order>
        <name>Premium</name>
        <price>49.00</price>
         <qty>15</qty>
</order>

order.dtd

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

ExampleGetDocType.java

import java.io.*; 
import java.io.*; 
 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" 
      
    else{
         System.out.println " DTD provided" 
         }
      }  catch Exception ce )  
     {
   System.out.println ce.getMessage (  )  ) ;
   }  
   }  


Output:

C:\>javac ExampleGetDocType.java

C:\>java ExampleGetDocType

      DTD provided

Download The Example:

Advertisement

Related Tags for Example of getDocType method in DOM API.:


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.

Posted on: September 23, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com