Java XML DocumentBuilder DTD Validation

Description

Java XML DocumentBuilder DTD Validation

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class Main {
   public static void main(String args[]) {
      try {//w  w w.  j  av a2 s  .c  o m
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setValidating(true);

         DocumentBuilder parser = factory.newDocumentBuilder();
         Document doc = parser.parse("q.xml");
      } catch (Exception e) {
         System.out.println(e);
      }
   }
}

File q.xml:

<?xml version="1.0"?>  
<!DOCTYPE question-paper  [ /*  w w  w  .j  ava 2s . c  om*/
   <!ELEMENT question-paper (question+)>  
   <!ELEMENT question (#PCDATA)>  
   <!ATTLIST question id ID #REQUIRED>  

]> 
<question-paper> 
   <question id="q1">What is DOM?</question>  
   <question id="q2">What are leaves?</question>  
   <question>What is DTD?</question>  
</question-paper> 



PreviousNext

Related