validating a XML document against a schema
I need some code sample which shows how i can validate a xml file against a schema...
Below is say my XML document.. "a.xml"
January 21 1983
Say the schema against which i want to validate the above xml is as below named "XMLValidationSchema.xsd"
开发者_运维知识库
Now can some one help me write the java code that will take these as input and give proper output like if the XML doc is a valid doc as per the schema i specified...
Thanks...
A simple example using JAXP:
import java.io.File;
import java.io.IOException;
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.xml.sax.SAXException;
public class XMLValidator {
public void validateXML(final String schemaPath, final String xmlToValidatePath) throws SAXException, IOException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaSource = new StreamSource(new File(schemaPath));
Schema schema = schemaFactory.newSchema(schemaSource);
Validator validator = schema.newValidator();
validator.validate(new StreamSource(xmlToValidatePath));
}
}
精彩评论