person.xml validates
注:默认情况下,验证后会输出验证的文件内容,可以使用 --noout选项去掉此输出,这样我们可以只得到最后的验证结果。
[U]复制代码[/U] 代码如下:#xmllint --noout --schema person.xsd person.xml
person.xml validates
下面我们改动person.xml,使这份文件age字段和sex都是不符合xsd定义的。
[U]复制代码[/U] 代码如下:#xmllint --noout --schema person.xsd person.xml
person.xml:4: element age: Schemas validity error : Element 'age': 'not age' is not a valid value of the atomic type 'xs:integer'.
person.xml:5: element sex: Schemas validity error : Element 'sex': [facet 'enumeration'] The value 'test' is not an element of the set {'male', 'female'}.
person.xml:5: element sex: Schemas validity error : Element 'sex': 'test' is not a valid value of the local atomic type.
person.xml fails to validate
可以看到xmllint成功的报出了错误! 4、 关于--schema的输出
在讲输出之前先看下面一个场景,假如你想通过php执行xmllint然后拿到返回结果,你的代码通常应该是这个样子valid.php
[U]复制代码[/U] 代码如下:
我们保持上文中person.xml的错误。
执行此代码,你会发现,你拿到的output不是错误,而是array(0) {}, amazing!
为什么会这样呢?
因为xmllint --schema,如果验证出错误,错误信息并不是通过标准输出(stdout)显示的,而是通过标准错误(stderr)进行显示的。
而exec的output参数拿到的,只能是标准输出(stdout)显示的内容。
所以,为了拿到出错信息,我们需要将标准错误重定向到标准输出,对应修改代码:
[U]复制代码[/U] 代码如下command = "xmllint --noout --schema person.xsd person.xml 2>$1";
再次执行valid.php,错误信息顺利拿到!
例子如下:
首先建立一份 xml 文档,命名为 po.xml,其内容如下:
[U]复制代码[/U] 代码如下:
Alice Smith
123 Maple Street
Mill Valley
CA
90952
Robert Smith
8 Oak Avenue
Old Town
PA
95819
Hurry, my lawn is going wild!
Lawnmower
1
[U]148.95[/U]
Confirm this is electric