RE:Validacion Schema XSD
Publicado por
Suko (1 intervención) el 04/12/2007 10:57:42
Hola francisco,
te paso el código para la validacion de un xml contra su xsd en java. Me costó un poco encontrarlo, por que todo el mundo pregunta pero nadie responde.
Esto a mi me funciona. Un saludo
public class ValidarXml {
private static void validarXmlvsXsd(String sFichXml, String sFichXsd)
{
String YES = "yes";
String NO = "no";
String CHAR_ENCODING = "UTF8";
boolean NAME_SPACE_AWARE = true;
boolean VALIDATING = true;
String SCHEMA_LANGUAGE ="http://java.sun.com/xml/jaxp/properties/schemaLanguage";
String SCHEMA_LANGUAGE_VAL = "http://www.w3.org/2001/XMLSchema";
String SCHEMA_SOURCE ="http://java.sun.com/xml/jaxp/properties/schemaSource";
try
{
Reader xmlReader;
Reader xsdReader;
xmlReader = new FileReader(sFichXml);
xsdReader = new FileReader(sFichXsd);
SAXParserFactory factory = SAXParserFactory.newInstance();
// Configure SAXParserFactory to provide parsers that are namespace aware.
factory.setNamespaceAware(NAME_SPACE_AWARE);
// Configure SAXParserFactory to provide parsers that are validating. This property
// must have the value true for any of the property strings defined below to take
// effect.
factory.setValidating(VALIDATING);
SAXParser parser = factory.newSAXParser();
// Setting the schema language for xml schema validation
parser.setProperty(SCHEMA_LANGUAGE, SCHEMA_LANGUAGE_VAL);
// Setting the schema source for xml schema validation
parser.setProperty(SCHEMA_SOURCE, new InputSource(xsdReader));
DefaultHandler handler = new XmlDefaultHandler();
parser.parse(new InputSource(xmlReader), handler);
catch (FactoryConfigurationError e) { System.out.println(e.toString()); }
catch (ParserConfigurationException e) { System.out.println(e.toString()); }
catch (SAXException e) { System.out.println(e.toString()); }
catch (IOException e) { System.out.println(e.toString()); }
}
public static class XmlDefaultHandler extends DefaultHandler
{
/** @see org.xml.sax.ErrorHandler#error(SAXParseException)
*/
public void error(SAXParseException spe) throws SAXException
{
throw spe;
}
/** @see org.xml.sax.ErrorHandler#fatalError(SAXParseException)
*/
public void fatalError(SAXParseException spe) throws SAXException
{
throw spe;
}
}
}
Un saludo