domingo, setembro 13, 2009

[java] Validador Schemas

Código funcional e com riqueza de detalhes que facilitam a vida do desenvolvedor.


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package validadorxml;

import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.XMLConstants;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import javax.xml.validation.Validator;
import java.io.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;

/**
*
* @author Armando Roque
* Copy´nPaste: http://www.herongyang.com/XML-Schema/JAXP-XSD-Schema-XML-Validator-Final-Version.html
* Tradução livre pt-br
*
*/
public class Main {
private static int errorCount = 0;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
if (args.length<2) {
System.out.println("Use:");
System.out.println("java -jar ValidadorXML nome_do_arquivo_do_schema.xsd "
+ "nome_do_arquivo.xml");
} else {
String schemaName = args[0];
String xmlName = args[1];
Schema schema = loadSchema(schemaName);
validateXml(schema, xmlName);
}
}
public static void validateXml(Schema schema, String xmlName) {
try {
// creating a Validator instance
Validator validator = schema.newValidator();

// setting my own error handler
validator.setErrorHandler(new MyErrorHandler());

// preparing the XML file as a SAX source
SAXSource source = new SAXSource(
new InputSource(new java.io.FileInputStream(xmlName)));

// validating the SAX source against the schema
validator.validate(source);
System.out.println();
if (errorCount>0) {
System.out.println("ERRO: Os seguintes erros foram detectados "+errorCount);
} else {
System.out.println("OK.");
}

} catch (Exception e) {
// catching all validation exceptions
System.out.println();
System.out.println(e.toString());
}
}
public static Schema loadSchema(String name) {
Schema schema = null;
try {
String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory factory = SchemaFactory.newInstance(language);
schema = factory.newSchema(new File(name));
} catch (Exception e) {
System.out.println(e.toString());
}
return schema;
}
private static class MyErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
System.out.println("Avisos: ");
printException(e);
}
public void error(SAXParseException e) throws SAXException {
System.out.println("ERROS: ");
printException(e);
}
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("ERRO FATAL: ");
printException(e);
}
private void printException(SAXParseException e) {
errorCount++;
System.out.println(" Numero da linha: "+e.getLineNumber());
System.out.println(" Numero da coluna: "+e.getColumnNumber());
System.out.println(" Mensagem: "+e.getMessage());
System.out.println();
}
}
}

Nenhum comentário: