Validation Function
public class ValidateXML {
public static boolean validateXml(String xsdPath, String xmlPath) {
try {
// 建立schema工廠
SchemaFactory schemaFactory = SchemaFactory
.newInstance("http://www.w3.org/2001/XMLSchema");
// 建立驗證文檔文件對象,利用此文件對象所封裝的文件進行schema驗證
File schemaFile = new File(xsdPath);
// 利用schema工廠,接收驗證文檔文件對象生成Schema對象
Schema schema = schemaFactory.newSchema(schemaFile);
// 通過Schema產(chǎn)生針對于此Schema的驗證器,利用schenaFile進行驗證
Validator validator = schema.newValidator();
// 得到驗證的數(shù)據(jù)源
Source source = new StreamSource(xmlPath);
// 開始驗證,成功輸出success!!!,失敗輸出fail
validator.validate(source);
} catch (SAXException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
String xsdFilePath = "/Users/wangxuefeng/test_playbooks/xml/test.xsd";
String xmlFilePath = "/Users/wangxuefeng/test_playbooks/xml/test.xml";
boolean isValid = validateXml(xsdFilePath, xmlFilePath);
System.out.println(isValid);
}
}
xml file
<?xml version="1.0"?>
<user xmlns="http://www.w3school.com.cn"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3school.com.cn test.xsd">
<name>Scott</name>
<age>18</age>
<birthday>2008-09-23</birthday>
<is_married>true</is_married>
</user>
xsd file
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3school.com.cn"
xmlns="http://www.w3school.com.cn"
elementFormDefault="qualified">
<xs:element name="user">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" >
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="100"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="birthday" type="xs:date"/>
<xs:element name="is_married" type="xs:boolean"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。