使用libxml根据schema验证xml的合法性


<?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就会越界,需要自己纠正这个错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值