RELAX NG in Java 1.5/JAXP 1.3

import javax.xml.*;
import javax.xml.validation.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import org.xml.sax.*;

public class Relax implements ErrorHandler {

  public static void main(String[] args) {
  
    if (args.length < 2) {
      System.out.println("Usage: java Relax schema.rng file.xml");
      return;
    }
    
    Schema schema;
    try {
      SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.RELAXNG_NS_URI);
      schema = factory.newSchema(new File(args[1]));
    }
    catch (SAXException ex) {
      System.out.println("Schema error in " + args[0]);  
      System.out.println(ex.getMessage());
      return;
    }
    catch (IllegalArgumentException ex) {
      System.out.println("This implementation does not support RELAX NG.");
      return;
    }
    Validator validator = schema.newValidator();
    Source source = new StreamSource(new File(args[1]));
    validator.setErrorHandler(new Relax());
    try {
      validator.validate(source);
    }
    catch (SAXException ex) {
      System.out.println(args[1] + " is not well-formed.");  
      System.out.println(ex.getMessage());
    }
    catch (IOException ex) {
      System.out.println("Could not validate " + args[1] + " due to an I/O error.");  
      System.out.println(ex.getMessage());
    }
    
  }
  
  public void warning(SAXParseException exception) {
    
    System.out.println("Warning: " + exception.getMessage());
    System.out.println(" at line " + exception.getLineNumber() 
     + ", column " + exception.getColumnNumber());
    
  }
  
  public void error(SAXParseException exception) {
     
    System.out.println("Error: " + exception.getMessage());
    System.out.println(" at line " + exception.getLineNumber() 
     + ", column " + exception.getColumnNumber());
    
  }
  
  public void fatalError(SAXParseException exception) {
     
    System.out.println("Fatal Error: " + exception.getMessage());
    System.out.println(" at line " + exception.getLineNumber() 
     + ", column " + exception.getColumnNumber());
     
  }

}

Previous | Next | Top | Cafe con Leche

Copyright 2005, 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 26, 2004