Create Project : DemoSAXinJAXP
Create file XML : Data.xml
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE mountains[
<!ELEMENT mountains (mountain)*>
<!ELEMENT mountain (name)*>
<!NOTATION GIF SYSTEM "image/gif">
<!NOTATION JPG SYSTEM "image/jpeg">
<!NOTATION PNG SYSTEM "image/png">
<!ATTLIST mountain
photo ENTITY #IMPLIED
photo_type NOTATION (GIF | JPG | PNG) #IMPLIED>
<!ENTITY mt_cook_1 SYSTEM "mt_cook1.jpg"NDATA gif>
<!ELEMENT name (#PCDATA)>
]>
<mountains>
<mountain photo="mt_cook_1"photo_type="JPG">
<name>Thai Son</name>
</mountain>
<mountain>
<name>Everest</name>
</mountain>
</mountains>
Create class : DTDHandlerExample
package Aptech.JavaXML.Module3;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
publicclassDTDHandlerExampleextends DefaultHandler {
staticboolean notationFound = false;
staticboolean unparsedEntityFound = false;
/*
* The parser calls this method whenever it encounters a notation
* declaration during parsing of a DTD
*/
@Override
publicvoidnotationDecl(String name, String publicID, String systemID) {
// inform the user that new notation is found in DTD
notationFound = true;
System.out.println("Notation found: "+ name);
}
/*
* The parser calls this method to notify an unparsed entity declaration
*/
@Override
publicvoidunparsedEntityDecl(String name, String publicID, String systemID, String notationName) {
// inform user that an uparsed entity was found
unparsedEntityFound = true;
System.out.println("Unparsed Entity "+ name + " uses "+ notationName);
}
/*
* The parser calls this method whenever it encounters the end of
* document during processing.
*/
@Override
publicvoidendDocument() throws SAXException {
// print appropriate message to the user if no new notation or unparsed entities found.
if(!notationFound) {
System.out.println("No new notations found");
}
if(!unparsedEntityFound) {
System.out.println("No unparsed entities found");
}
}
}
Create class : DTDHandlerExample
package Aptech.JavaXML.Module3;
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
publicclassTestDTDHandlerExample{
publicstaticvoidmain(String[] args) {
String path = "src\\Aptech\\JavaXML\\Module3\\Data.xml";
// Create class instance for the SAX event handler
DTDHandlerExample saxObject = newDTDHandlerExample();
// Create factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try{
// Create parse
SAXParser parser = spf.newSAXParser();
// Parse document
parser.parse(newFile(path), saxObject);
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
0 nhận xét:
Đăng nhận xét