在xml的相关开发中,经常需要用到根据输入的schema,要求验证的xml文件的合法性问题,本文就
这个问题把我们在开发中用到xml验证方法拿来与大家分享,代码如下
import java.io.IOException;
import java.io.InputStream;
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;
/**
* @version v1.0
* @author -ziliang
*
*/
public class XmlCheck{
//定义xml对应xsd文档
public final static String XSD_FILE = "test.xsd";
//xsd验证方法
public static boolean valid(InputStream inputStream, String xsdFilePath)
throws IOException{
SchemaFactory schemaFactory = SchemaFactory
.newInstance("http://www.w3.org/2001/XMLSchema");
try{
Source sourceXSD = new StreamSource(getFileInClassPath(xsdFilePath));
Schema schema = schemaFactory.newSchema(sourceXSD);
Validator validator = schema.newValidator();
Source source = new StreamSource(inputStream);
validator.validate(source);
return true;
}catch(SAXException e){
e.printStackTrace();
return false;
}
}
//注意xsd存放位置,本例子的xsd存放本类的同一个目录下
public static InputStream getFileInClassPath(String filePath){
return XmlCheck.class.getResourceAsStream(filePath);
}
}
上面验证xml格式的类已经完成,好了,下面用Junit来写一个测试类代码如下:
public class TestXml {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
//如无须测试本方式时,用@Ignore注释掉
//@Ignore
@Test
public void testCheckXSD() throws IOException {
String xml ="<?xml version=/"1.0/" encoding=/"UTF-8/"?>"+
"<Domain>"
+ "<REQUEST>"
+ "<XML_Domain>"
+ "<REQ_ID>11</REQ_ID>"
+ "<START_DATE>20101225</START_DATE>"
+ "<END_DATE>20101223</END_DATE>"
+ "<REQ_DESC>20750</REQ_DESC>"
+ "</XML_Domain>"
+ "</REQUEST>"
+"</Domain>";
ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
boolean t = XmlCheck.valid(inputStream, XmlCheck.XSD_FILE);
}
}
另外文件test.xsd如下:
<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2008 rel. 2 sp2 (http://www.altova.com) by SHOCK (SHOCK) -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="Domain">
<xs:annotation>
<xs:documentation>Comment describing your root element</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="REQUEST">
<xs:complexType>
<xs:sequence>
<xs:element name="XML_Domain">
<xs:complexType>
<xs:sequence>
<xs:element name="REQ_ID"/>
<xs:element name="START_DATE"/>
<xs:element name="END_DATE"/>
<xs:element name="REQ_DESC"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>