标签:
package com.huey.dream.utils; import java.io.File; import java.io.IOException; 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 XSDValidator { static public void validate(String xmlPath, String xsdPath) throws SAXException, IOException { SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); File schemaFile = new File(xsdPath); Schema schema = schemaFactory.newSchema(schemaFile); Source source = new StreamSource(xmlPath); Validator validator = schema.newValidator(); validator.validate(source); } }
测试。
package com.huey.dream; import java.io.IOException; import org.junit.Test; import org.xml.sax.SAXException; import com.huey.dream.utils.XSDValidator; public class XSDValidatorTest { @Test public void testValidate() throws Exception { 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(); } } }
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="books"> <xs:complexType> <xs:sequence> <xs:element name="book"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string"/> <xs:element name="authors"> <xs:complexType> <xs:sequence> <xs:element name="author" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="firstName" type="xs:string"/> <xs:element name="lastName" type="xs:string"/> <xs:element name="nationality" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="publisher" type="xs:string" minOccurs="0"/> <xs:element name="publishDate" type="xs:date" minOccurs="0"/> <xs:element name="isbn" type="xs:string"/> <xs:element name="price" type="xs:double" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
<?xml version="1.0" encoding="UTF-8"?> <books> <book> <title>HTTP权威指南</title> <authors> <author> <firstName>David</firstName> <lastName>Gourley</lastName> </author> <author> <firstName>Brian</firstName> <lastName>Totty</lastName> </author> </authors> <publisher>人民邮电出版社</publisher> <publishDate>2012-09-01</publishDate> <isbn>9787115281487</isbn> <price>109.00</price> </book> </books>
标签:
原文地址:http://www.cnblogs.com/huey/p/4600817.html