本篇文章帮大家学习XSD验证,包含了XSD验证使用方法、操作技巧、实例演示和注意事项,有一定的学习价值,大家可以用来参考。
在这小节中,我们将使用基于java的XSD验证器来针对students.xsd验证文件:students.xml。
文件:students.xml -
Dinkar
King
Dinkar
85
Vaneet
Su
Vaneet
95
Jasvir
Lee
Jasvir
90
文件:students.xsd -
maxOccurs = 'unbounded' />
文件:XSDValidator.java -
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
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 {
public static void main(String[] args) {
if(args.length !=2){
System.out.println("Usage : XSDValidator " );
} else {
boolean isValid = validateXMLSchema(args[0],args[1]);
if(isValid){
System.out.println(args[1] + " is valid against " + args[0]);
} else {
System.out.println(args[1] + " is not valid against " + args[0]);
}
}
}
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException e){
System.out.println("Exception: "+e.getMessage());
return false;
}catch(SAXException e1){
System.out.println("SAX Exception: "+e1.getMessage());
return false;
}
return true;
}
}
针对XSD验证XML的步骤
将XSDValidator.java文件复制到一个工作目录位置,例如:D:\worksp\xsd,将students.xml 和students.xsd 这两个文件复制到相同的工作目录位置(D:\worksp\xsd)。打开命令行控制台编译XSDValidator.java,确保在计算机上安装了JDK 1.5以及类路径。 有关如何使用JAVA的详细信息,请参阅JAVA教程。
D:\worksp\xsd>javac XSDValidator.java
执行XSDValidator,并将students.xsd和students.xml这两个文件名称作为参数传递。输出结果如下所示 :
D:\worksp\xsd>java XSDValidator students.xsd students.xml
students.xml is valid against students.xsd