<?php
/*
Author: fuliang http://fuliang.iteye.com
*/
class XMLValidation{
private $xml_path;
private $schema_path;
public function __construct($xml_path,$schema_path){
$this->xml_path = $xml_path;
$this->schema_path = $schema_path;
}
function validate(){
libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->load($this->xml_path);
if($xml->schemaValidate($this->schema_path)){
echo "The xml is valid\n";
}else{
$this->pretty_print_errors();
}
}
function pretty_print_errors(){
$errors = libxml_get_errors();
$error_count = count($errors);
echo "Total num of errors is: $error_count\n";
for($i = 0; $i < $error_count; $i++){
$this->fmt_error_with_num($i+1,$errors[$i]);
}
libxml_clear_errors();
}
function fmt_error_with_num($num, $error){
echo "Error $num: ".trim($error->message)." in file " . $error->file . " on line " .$error->line. "\n";
}
}
$xml_validation = new XMLValidation("test.xml","test.xsd");
$xml_validation->validate();
?>
test.xsd:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="stringType">
<xs:restriction base="xs:string">
<xs:pattern value="[a-z]{6}"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="stringType" minOccurs="0"/>
<xs:element name="age" type="xs:positiveInteger"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
<xs:attribute name="person_id" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
test.xml
<?xml version="1.0"?>
<person>
<name>133</name>
<age>22</age>
<address>beijing haidian</address>
<city>beijing</city>
<country>China</country>
</person>
输出结果:
[quote]
Error 1: Element 'person': The attribute 'person_id' is required but missing. in file /home/fuliang/program/php/test.xml on line 2
Error 2: Element 'name': [facet 'pattern'] The value '133' is not accepted by the pattern '[a-z]{6}'. in file /home/fuliang/program/php/test.xml on line 3
Error 3: Element 'name': '133' is not a valid value of the atomic type 'stringType'. in file /home/fuliang/program/php/test.xml on line 3
[/quote]
重新修改一下xml
<?xml version="1.0"?>
<person person_id="123">
<name>aaaaaa</name>
<age>22</age>
<address>beijing haidian</address>
<city>beijing</city>
<country>China</country>
</person>
输出信息:
[quote]
The xml is valid
[/quote]
需要注意的是行号类型是short的,超过65535就会越界,需要自己纠正这个错误。