XSD file (XML Schema language is also called XML Schema Definition (XSD). For specific usage and definitions, please refer to:
http://www.w3school.com.cn/schema/index.asp
java from jdk1.5 The new SchemaFactory class above can support XSD verification, and it is very convenient to use.
The following code can be used in JDK1.5+ to verify xml
[java] view plaincopy
public class SimpleErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
}
public void error(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
}
public void fatalError(SAXParseException e) throws SAXException {
System .out.println(e.getMessage());
}
}
SAXParserFactory factory = SAXParserFactory.newInstance();
SchemaFactory schemaFactory =
SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(
new Source[] {new StreamSource( "contacts.xsd")}));
SAXParser parser = factory.newSAXParser();
SAXReader reader = new SAXReader(parser.getXMLReader());
reader.setValidation(false);
reader.setErrorHandler(new SimpleErrorHandler());
reader .read("contacts.xml"); For
details, please refer to: http://www.edankert.com/validate.html
XSD support is not provided before JDK1.5, because there are many XML APIs before JDK1.5 DOM4j + xerces can be used all over the sky If you use XPATH to read XML nodes, you need saxpath.jar
JDK1.4+DOM4J+xerces to verify the xml file
[c-sharp] view plaincopy
public class ParserErrorHandler implements ErrorHandler {
private static final Logger logger = Logger.getLogger(ParserErrorHandler.class);
public void error(SAXParseException e) throws SAXException {
//logger.error(e);
throw e;
}
public void fatalError(SAXParseException e) throws SAXException {
//logger.error(e);
throw e;
}
public void warning(SAXParseException e) throws SAXException {
//logger.error(e);
throw e;
}
}
-- After defining SAXReader, it will run abnormally if it reads the xml file if it does not conform to the XSD rules
SAXReader reader = new SAXReader();
reader.setValidation(true);
reader.setFeature("http://xml.org/sax/features/validation", true);
reader.setFeature("http://apache.org/xml/features/validation/schema",
true);
reader
.setProperty(
"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
“xxx.XSD");
reader.setErrorHandler(new ParserErrorHandler());
Validating XML files with XSD
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=326961517&siteId=291194637
Recommended
Ranking