[jdom-interest] DTD Validation with SAXBuilder()

Per Norrman pernorrman at telia.com
Thu Jun 17 15:19:32 PDT 2004


Hi,

It's hard to tell without the overall context. However, the commonly
accepted idiom for catching "invalidness" is demonstrated in this
self-contained example:

===========================================================
import java.io.IOException;
import java.io.StringReader;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class Invalid {

    private static String docType =
       "<!DOCTYPE root ["
          + " <!ELEMENT root (child) > "
          + " <!ELEMENT child EMPTY > "
          + " ]> ";

    public static void test(String xml) {
       try {
          SAXBuilder builder = new SAXBuilder(true);
          Document doc = builder.build(new StringReader(docType + xml));
          System.out.println("OK");
       } catch (JDOMException e) {
          System.out.println(e.getMessage());
       } catch (IOException e) {
          System.out.println(e.getMessage());
       }
    }

    public static void main(String[] args) {
       test("<root><child/></root>");
       test("<root><child>This text is invalid</child></root>");
    }
}
===========================================================

Should produce:

OK
Error on line 1: The content of element type "child" must match "EMPTY".

I have never used a custom error handler.


/pmn

Jing Chen wrote:
> Hi,
> 
> I am trying to validate the XML with DTD with the following code. I 
> wrote an invalidate xml for testing, but the code did not catch it 
> (where MyErrorHandler extends BuilderErrorHandler). Can you tell what 
> went wrong? Thanks!!
> 
> SAXBuilder builder = new SAXBuilder (true);
> builder.setValidation(true);
> MyErrorHandler handler = new MyErrorHandler();
> builder.setErrorHandler(handler);
> reportsParamDoc = new SAXBuilder().build(file);
> if (!handler.isValid)
> System.exit(-1);
> 



More information about the jdom-interest mailing list