我将 XML 作为字符串,将 XSD 作为文件,我需要使用 XSD 验证 XML。我怎样才能做到这一点?
11454 次
2 回答
11
您可以使用 javax.xml.validation API 来执行此操作。
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;
}
于 2011-03-18T13:18:34.053 回答
2
您可以为此使用javax.xml.validation API:
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)));
于 2011-03-18T13:11:00.417 回答