一、首先要有一个xml文件和xsd文件
(1) database.conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<datasourse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost:3306/salary_management?characterEncoding=UTF8&useUnicode=true&useSSL=false</url>
<user>root</user>
<password>200153</password>
</datasourse>
(2) database.conf.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="datasourse">
<xs:complexType>
<xs:sequence>
<xs:element name="driver" type="xs:string"></xs:element>
<xs:element name="url" type="xs:string"></xs:element>
<xs:element name="user" type="xs:string"></xs:element>
<xs:element name="password" type="xs:string"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
二、手写Java验证器
写一个Java程序引用xsd文件验证xml文件的有效性,若是xml文件格式有效返回true,否则返回false。
package cn.edu.lingnan.util;
import org.xml.sax.SAXException;
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 java.io.File;
import java.io.IOException;
public class XmlVlidate {
//输入XDS和XML文件。来验证XML文件的有效性
public static boolean validate(String xsdPath,String xmlPath){
boolean flag = false;
try {
//1.创建模式工厂
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
//2.通过XSD文件创建模式Scheme
File file = new File(xsdPath);
Schema schema = schemaFactory.newSchema(file);
//3.由模式创建验证器Validator
Validator validator = schema.newValidator();
//4.使用验证器验证xml文件
Source source = new StreamSource(xmlPath);
validator.validate(source);
flag = true;
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("[Debug]xsd文件在验证xml文件时出错");
e.printStackTrace();
}
return flag;
}
}