如何验证XML文件是否匹配XSD
验证XML文件是否匹配一个XSD文件。
假设XSD文件定义为example02.xsd
输入XML文件为example02.xml,下面代码例子验证example02.xml是否匹配example02.xsd格式。
import java.io.File;
import java.io.IOException;
import java.net.URL;
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 ValidateTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ValidateTest t = new ValidateTest ();
try {
t.validateXML("example02.xml", "example02.xsd");
} catch (SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void validateXML(String xml, String xsd) throws SAXException, IOException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(xsd));
// When if XSD is coming from a URL:
//Schema schema2 = schemaFactory.newSchema(new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"));
Source xmlFile = new StreamSource(new File(xml));
Validator validator = schema.newValidator();
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
}
}