I have the following XML file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE starfleet SYSTEM "http://localhost:8080/xml-validate/dtd/starfleet.dtd"> <starfleet> <title>The two most famous starships in the fleet</title> <starship name="USS Enterprise" sn="NCC-1701"> <class name="Constitution"/> <captain>James Tiberius Kirk</captain> </starship> <starship name="USS Enterprise" sn="NCC-1701-D"> <class name="Galaxy"/> <captain>Jean-Luc Picard</captain> </starship> </starfleet>
And the following DTD:
<!ELEMENT starfleet (title,starship*)> <!ELEMENT title (#PCDATA)> <!ELEMENT starship (class,captain)> <!ATTLIST starship name CDATA #REQUIRED sn CDATA #REQUIRED> <!ELEMENT class EMPTY> <!ATTLIST class name CDATA #REQUIRED> <!ELEMENT captain (#PCDATA)>
I wanted to parse and validate the XML by using JAXP and a simple JSP file.
My SAX Exception Handler is:
package myPkg; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXParseException; public class ParsingExceptionHandler extends DefaultHandler { public SAXParseException parsingException = null; public String errorLevel = null; public void warning(SAXParseException e) { errorLevel = "Warning"; parsingException = e; } public void error(SAXParseException e) { errorLevel = "Error"; parsingException = e; } public void fatalError(SAXParseException e) { errorLevel = "Fatal error"; parsingException = e; } }
And the JSP file that executes the actual validation is:
<%@page language="java" contentType="text/html"%> <%@page import="javax.xml.parsers.SAXParserFactory"%> <%@page import="javax.xml.parsers.SAXParser"%> <%@page import="org.xml.sax.InputSource"%> <%@page import="org.apache.commons.lang3.StringEscapeUtils"%> <%@page import="myPkg.ParsingExceptionHandler"%> <html><head><title>Starfleet validation (SAX - DTD)</title></head><body> <% SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); InputSource inputSource = new InputSource("webapps/xml-validate/xml/enterprises.xml"); ParsingExceptionHandler handler = new ParsingExceptionHandler(); try { parser.parse(inputSource, handler); } catch (Exception e) { out.println("Something went wrong..."); } if (handler.errorLevel == null) { out.println("The document is valid."); } else { out.println( "*** Validation " + handler.errorLevel + ": " + StringEscapeUtils.escapeHtml4(handler.parsingException.toString()) ); } %> </body></html>
The problem is that no matter what I do, the catch part of the code is entered, which means that my XML file is never deemed "valid" by the parser. Something must be wrong with my XML, right? However, the Exception Handler is never used and so its parsingException and errorLevel attributes always remain null, causing the message "The document is valid" to be displayed in the browser. Any insight into why is this happening?
P.S.: This is running inside a Tomcat instance.
No comments:
Post a Comment