190 likes | 309 Views
ADVANCED SAX. Objectives. Error Handling Using DTDHandler Interface Lexical Events and EntityResolver Interface SAX Filters Workshops. Error in processing XML. Fatal Errors Occur in the SAX parser XML document is not well-formed
E N D
Objectives • Error Handling • Using DTDHandler Interface • Lexical Events and EntityResolver Interface • SAX Filters • Workshops
Error in processing XML • Fatal Errors • Occur in the SAX parser • XML document is not well-formed • XML document cannot be processed because it terminates the execution • Non-Fatal Errors • Validation errors in SAX parser are termed • An XML document is not valid. • A declaration specified by an XML version, which cannot be handled by the parser • Warnings • Are generated when a DTD contains duplicate definitions • Generated during XML validation are not errors but the user needs to be informed about it
public class SAXErrorHandling extends DefaultHandler { public static void main (String[] args) { SAXErrorHandling saxObject = new SAXErrorHandling(); SAXParserFactory spf = SAXParserFactory.newInstance (); try { SAXParser parser = spf.newSAXParser (); parser.parse (new File(args[0]), saxObject); }catch(SAXParseException e){ System.out.println("\n**Error occurred while parsing **" + ", line " + e.getLineNumber ()); System.out.println(" " + e.getMessage ()); } catch(SAXException e){ Exception Except = e; if(e.getException ()!=null){Except = e.getException ();} Except.printStackTrace (); } catch(ParserConfigurationException e){e.printStackTrace (); } catch(IOException e){e.printStackTrace (); } catch(Throwable t){t.printStackTrace ();} System.exit (0);} public void endDocument () throws SAXException { System.out.println("No errors found during parsing");} public void error (SAXParseException e) throws SAXException {throw e;} } Example: non-validating
<tomcat-users> <role rolename="tomcat"/> <role rolename="role1"/> <role rolename="manager"/> role rolename="admin"/> <user username="tomcat" password="tomcat" roles="tomcat"/> <user username="both" password="tomcat" roles="tomcat,role1"/> <user username="role1" password="tomcat" roles="role1"/> <user username="admin" password="" roles="admin, manager"/> <user username="supervisor" password="" roles="admin, manager" </tomcat-users> Example (cont)
public class SAXErrors extends DefaultErrorHandler { public static void main (String[] args) { DefaultHandler handler = new DefaultHandler(); ErrorHandler error = new SAXErrors(); try { XMLReader parser = XMLReaderFactory.createXMLReader (); parser.setContentHandler (handler); parser.setErrorHandler (error); parser.setFeature ("http://xml.org/sax/features/validation", true); parser.parse (args[0]); }catch(Exception e){e.printStackTrace ();} } public void error (SAXParseException exception) throws SAXException { System.out.println ("Parsing error: \nLine: " + exception.getLineNumber() + "\nColumn: " + exception.getColumnNumber() + "\nURI: " + exception.getSystemId() + "\n Message: " + exception.getMessage()); } } Example
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="Books_format.xsl" ?> <!DOCTYPE library[ <!ELEMENT library (book)*> <!ELEMENT book (booktitle, author, price)+> <!ELEMENT booktitle (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT price (#PCDATA)> ]> <library> <book> <author>Robin Cook</author> <booktitle>Coma</booktitle> <price>99.5</price> </book> </library> Example (cont)
DTDHandler Interface • To retrieve information about notations and unparsed entities for a SAX-based application the DTDHandler interface is implemented • Register an instance with the SAX parser by the use of parser’s setDTDHandler() method.
public class NotEnt extends DefaultHandler implements DTDHandler { public static void main (String[] args) { NotEnt saxObject = new NotEnt(); try { XMLReader parser = XMLReaderFactory.createXMLReader (); parser.setFeature ("http://xml.org/sax/features/namespace-prefixes", true); parser.setDTDHandler (saxObject); parser.setContentHandler (saxObject); parser.parse (args[0]); }catch(Exception e){e.printStackTrace ();} } public void unparsedEntityDecl (String name, String publicId, String systemId, String notationName) throws SAXException { System.out.println("unparsedEntityDecl"); System.out.println ("Name: " + name + "-PublicId: " + publicId + "-SystemId: " + systemId + "-notation: " + notationName); } public void notationDecl (String name, String publicId, String systemId) throws SAXException { System.out.println("notationDecl"); System.out.println ("Name: " + name + "-PublicId: " + publicId + "-SystemId: " + systemId);} } Example
entityNotation.xml <?xml version="1.0"?> <!DOCTYPE family [ <!ELEMENT title (#PCDATA)> <!ELEMENT parent (#PCDATA)> <!ATTLIST parent role CDATA #IMPLIED> <!ELEMENT child (#PCDATA)> <!ATTLIST child role CDATA #IMPLIED> <!NOTATION PNG SYSTEM "image/png"> <!ENTITY logo SYSTEM "http://www.example.com/logo.png" NDATA PNG> <!ELEMENT figure EMPTY> <!ATTLIST figure logo ENTITY #REQUIRED> ]> <family> <title>My Family</title> <parent role="mother">Judy</parent> <parent role="father">Layard</parent> <child role="daughter">Jennifer</child> <image source="JENN" /> <child role="son">Brendan</child> </family> Example (cont)
EntityResolver interface • Is a basic interface for resolving entities • Registers an instance with the SAX driver using the setEntityResolver() method whenever implementation of customized handling for external entities is required • The resolveEntity() method of this interface allows applications to resolve external entities. The parser calls this method before fetching any external entity except the top level document entity public InputSource resolveEntity (String publicId, String systemId) throws IOException, SAXException
The filter is in between the real parser and the client application. Due to this reason, the stream of events gets changed and passed to and from between them XMLFilter Interface public abstract interface XMLFilter extends XMLReader SAX Filters
public class DemoFilter { public static void main (String[] args) { try { InputSource is = new InputSource(“Book.xml”); SAXParser parser = SAXParserFactory.newInstance ().newSAXParser (); XMLReader reader = parser.getXMLReader (); SAXTransformerFactory stf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); XMLFilter filter1 = stf.newXMLFilter (new StreamSource(“Filter.xsl”)); filter1.setParent (reader); StreamResult result = new StreamResult(System.out); Transformer transformer = stf.newTransformer (); SAXSource transformerSource = new SAXSource(filter1, is); transformer.transform (transformerSource, result); } catch(Exception e){ e.printStackTrace (); } } } Example
Book.xml file <?xml version="1.0" encoding="UTF-8"?> <Article> <ArtHeader> <Title>Title of my (Docbook) article</Title> </ArtHeader> <Sect1> <Title>Title of Section 1.</Title> <Para>This is a paragraph.</Para> </Sect1> </Article> Example (cont)
filter.xsl file <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml"/> <xsl:template match="/"> <ARTICLE> <xsl:apply-templates/> </ARTICLE> </xsl:template> <xsl:template match="/Article/ArtHeader/Title"> <TITLE> <xsl:apply-templates/> </TITLE> </xsl:template> </xsl:stylesheet> Example (cont)
Filtering Elements, Tags, and Attributes: The XML filter in combination with the ContentHandler interfaces enable the following Filtering Elements Filtering Tags Filtering Attributes SAX Filters (cont)
WORKSHOP ACTIVITIES • Building the console Java application using SAX Parser can do • Checking error the XML document • Checking and parsing the unparseEntity and notation • Parsing and print the DTD, CDATA and comment in XML Document