Packagecom.huey.dream.utils;ImportJava.io.File;Importjava.io.IOException;ImportJavax.xml.transform.Source;ImportJavax.xml.transform.stream.StreamSource;ImportJavax.xml.validation.Schema;Importjavax.xml.validation.SchemaFactory;ImportJavax.xml.validation.Validator;Importorg.xml.sax.SAXException; Public classXsdvalidator {Static Public voidValidate (String Xmlpath, String xsdpath)throwssaxexception, IOException {schemafactory schemafactory= Schemafactory.newinstance ("Http://www.w3.org/2001/XMLSchema"); File Schemafile=NewFile (Xsdpath); Schema schema=Schemafactory.newschema (schemafile); Source Source=NewStreamsource (Xmlpath); Validator Validator=Schema.newvalidator (); Validator.validate (source); } }
Test.
PackageCom.huey.dream;Importjava.io.IOException;Importorg.junit.Test;Importorg.xml.sax.SAXException;ImportCom.huey.dream.utils.XSDValidator; Public classxsdvalidatortest {@Test Public voidTestvalidate ()throwsException {String Xsdpath= "Files/books.xsd"; String Xmlpath= "Files/books.xml"; Try{xsdvalidator.validate (Xmlpath, Xsdpath); System.out.println ("Validate successfully."); } Catch(saxexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } }}Xsdvalidatortest.java
<?XML version= "1.0" encoding= "UTF-8"?><Xs:schemaXmlns:xs= "Http://www.w3.org/2001/XMLSchema"elementFormDefault= "qualified"attributeFormDefault= "unqualified"> <xs:elementname= "Books"> <Xs:complextype> <xs:sequence> <xs:elementname= "book"> <Xs:complextype> <xs:sequence> <xs:elementname= "title"type= "Xs:string"/> <xs:elementname= "Authors"> <Xs:complextype> <xs:sequence> <xs:elementname= "Author"maxOccurs= "unbounded"> <Xs:complextype> <xs:sequence> <xs:elementname= "FirstName"type= "Xs:string"/> <xs:elementname= "LastName"type= "Xs:string"/> <xs:elementname= "Nationality"type= "Xs:string"minOccurs= "0"/> </xs:sequence> </Xs:complextype> </xs:element> </xs:sequence> </Xs:complextype> </xs:element> <xs:elementname= "publisher"type= "Xs:string"minOccurs= "0"/> <xs:elementname= "Publishdate"type= "Xs:date"minOccurs= "0"/> <xs:elementname= "ISBN"type= "Xs:string"/> <xs:elementname= "Price"type= "Xs:double"minOccurs= "0"/> </xs:sequence> </Xs:complextype> </xs:element> </xs:sequence> </Xs:complextype> </xs:element></Xs:schema>
books.xsd
<?XML version= "1.0" encoding= "UTF-8"?><Books> < Book> <title>HTTP authoritative Guide</title> <authors> <author> <FirstName>David</FirstName> <LastName>Gourley</LastName> </author> <author> <FirstName>Brian</FirstName> <LastName>Totty</LastName> </author> </authors> <Publisher>People's post and telecommunications publishing house</Publisher> <publishdate>2012-09-01</publishdate> <ISBN>9787115281487</ISBN> < Price>109.00</ Price> </ Book></Books>
books.xml
Java-Validating XML using XSD