Snippet: validating xml with xsd in Java

     
import java.io.Reader;
import java.io.StringReader;


import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;


import org.springframework.core.io.ClassPathResource;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;


....


String xmlFormated = "";
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

       ClassPathResource cpr = new ClassPathResource("my_xsd_file.xsd");
       Source schemaFile = new StreamSource( cpr.getFile()  );
       Schema schema = factory.newSchema(schemaFile);

       Validator validator = schema.newValidator();
       Reader reader = new StringReader(xmlFormated);
       Source source = new StreamSource(reader);


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


...

No hay comentarios: