2011-03-18 14 views
5

Tengo XML como cadena y un XSD como archivo, y necesito validar el XML con el XSD. ¿Cómo puedo hacer esto?realizando validación xml contra xsd

+0

O u necesidad de un archivo XML en lugar de cuerdas y de lo que puede validar el XML con XSD, hay un montón de herramientas disponibles como JAXB 2.x, etc Xrces –

Respuesta

1

Puede utilizar las API para este javax.xml.validation:

String xml = "<root/>"; // XML as String 
File xsd = new File("schema.xsd"); // XSD as File 

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
Schema schema = sf.newSchema(xsd); 

SAXParserFactory spf = SAXParserFactory.newInstance(); 
spf.setSchema(schema); 
SAXParser sp = spf.newSAXParser(); 
XMLReader xr = sp.getXMLReader(); 
xr.parse(new InputSource(new StringReader(xml))); 
9

Puede utilizar la API javax.xml.validation para hacer esto.

public boolean validate(String inputXml, String schemaLocation) 
    throws SAXException, IOException { 
    // build the schema 
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); 
    File schemaFile = new File(schemaLocation); 
    Schema schema = factory.newSchema(schemaFile); 
    Validator validator = schema.newValidator(); 

    // create a source from a string 
    Source source = new StreamSource(new StringReader(inputXml)); 

    // check input 
    boolean isValid = true; 
    try { 

    validator.validate(source); 
    } 
    catch (SAXException e) { 

    System.err.println("Not valid"); 
    isValid = false; 
    } 

    return isValid; 
} 
+0

perfecto para mis usos - gracias – thonnor

Cuestiones relacionadas