validating a XML document against a schema

∥☆過路亽.° 提交于 2019-12-25 00:25:55

问题


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...


回答1:


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));
    }
}


来源:https://stackoverflow.com/questions/4012897/validating-a-xml-document-against-a-schema

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!