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 |