Xml file:
12. xml
<? Xml version = "1.0" encoding = "gb2312"?> <! -- If the root element score is followed by a namespace, the result is always invalid --> <score xmlns: xs = "http://www.w3.org/2001/XMLSchema-instance" xs: noNamespaceSchemaLocation = "12.xsd"> <eng> 87.3 </eng> <math> 99.8 </math> <physics> 90 </physics> </score>
12. xsd
<?xml version="1.0"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:element name="score"> <xsd:complexType> <xsd:sequence> <xsd:element ref="eng"/> <xsd:element ref="math"/> <xsd:element ref="physics"/> </xsd:sequence> </xsd:complexType></xsd:element><xsd:element name="eng" type="xsd:float"/><xsd:element name="math" type="xsd:float"/><xsd:element name="physics" type="xsd:float"/></xsd:schema>
ValidateSchema. java
// Verify 12. whether xml complies with the Schema mode import org. xml. sax. helpers. defaultHandler; import org. xml. sax. SAXParseException; import org. xml. sax. SAXException; import org. w3c. dom. *; import javax. xml. parsers. *; class MyHandler extends DefaultHandler {String em = null; // common error message: XML file validity error public void error (SAXParseException e) throws SAXException {em = e. getMessage (); System. out. println ("general error:" + em) ;}// serious error. XML file's normative error public void fataError (SAXParseException e) throws SAXException {em = e. getMessage (); System. out. println ("Fatal error" + em) ;}} public class ValidateSchema {public static void main (String [] args) {// XML file path String xmlFile = "12.xml "; // Schema file path String xsdFile = "12.xsd"; // define the processor MyHandler mh = null; try {// create the DocumentBuilderFactory factory object DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory. newInstance (); // supports namespace docBuilderFactory. setNamespaceAware (true); // you can specify docBuilderFactory. setValidating (true); // you can specify the Schema file docBuilderFactory. setAttribute ("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); docBuilderFactory. setAttribute ("http://java.sun.com/xml/jaxp/properties/schemaSource", xsdFile); // create the COM Object DocumentBuilder docBuilder = docBuilderFactory. newDocumentBuilder (); // instantiate the processor object mh = new MyHandler (); // DOM binds docBuilder to the processor. setErrorHandler (mh); // start to test Document doc = docBuilder. parse (xmlFile); // if the returned information is null if (mh. em = null) {System. out. println ("file" + xmlFile + "compliant with" + xsdFile + "file mode, which is a valid XML file");} else {System. out. println ("file" + xmlFile + "does not match" + xsdFile + "file mode, which is an invalid XML file") ;}} catch (Exception e) {System. out. println (e );}}}
This article is from the "Aegean Sea" blog, please be sure to keep this source http://piano.blog.51cto.com/3954765/1303923