xmllint是一個很方便的處理及驗證xml的工具,linux下只要安裝libxml2就可以使用這個命令,下面整理一些常用功能
1. --format
此參數用於格式化xml,使其具有良好的可讀性。
假設有xml(person.xml)內容如下:
<person><name>ball</name><age>30</age><sex>male</sex></person>
執行:
xmllint --format person.xml  
<person> <name>ball</name> <age>30</age> <sex>male</sex> </person>2. --noblanks
與--format相反,有時為了節省傳輸量,我們希望去掉xml中的空白,這時我們可以使用--noblanks命令。
假設xml(person.xml)內容如下
<?xml version="1.0"?> <person> <name>ball</name> <age>30</age> <sex>male</sex> </person>
執行:
xmllint --noblanks person.xml  
ball 30 male 
3.--schema
使用scheam驗證xml文件的正確性(瞭解schema的知識請猛擊這裡)
假設有xml文件(person.xml)和scheam文件(person.xsd)文件,內容分別如下
person.xml
person.xsd
<?xml version="1.0"?> <person> <name>ball</name> <age>30</age> <sex>male</sex> </person>
person.xsd
<?xml version="1.0"?>  
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">  
  <xs:element name="name" type="xs:string"/>  
  <xs:element name="age" type="xs:integer"/>  
  <xs:element name="sex">  
    <xs:simpleType>  
      <xs:restriction base="xs:string">  
        <xs:enumeration value="male"/>  
        <xs:enumeration value="female"/>  
      </xs:restriction>  
    </xs:simpleType>  
  </xs:element>  
  <xs:element name="person">  
    <xs:complexType>  
      <xs:all>  
        <xs:element ref="name"/>  
        <xs:element ref="age"/>  
        <xs:element ref="sex"/>  
      </xs:all>  
    </xs:complexType>  
  </xs:element>  
</xs:schema>
執行:
xmllint --schema person.xsd person.xml  
得到
  
  ball   
  30   
  male   
   
person.xml validates 
執行
xmllint --noout --schema person.xsd person.xml   
得到
person.xml validates  
下面我們改動person.xml
顯然,這份文件age字段和sex都是不符合xsd定義的。
執行
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 
good!xmllint成功的報出了錯誤!
4. 關於--schema的輸出
在講輸出之前先看下面一個場景,假如你想通過php執行xmllint然後拿到返回結果,你的代碼通常應該是這個樣子
valid.php
執行此代碼,你會發現,你拿到的output不是錯誤,而是array(0) {}, amazing!
為什麼會這樣呢?
因為xmllint --schema,如果驗證出錯誤,錯誤信息並不是通過標準輸出(stdout)顯示的,而是通過標準錯誤(stderr)進行顯示的。
而exec的output參數拿到的,只能是標準輸出(stdout)顯示的內容。
所以,為了拿到出錯信息,我們需要將標準錯誤重定向到標準輸出,對應修改代碼:
$command = "xmllint --noout --schema person.xsd person.xml 2>&1";  
附小問題
--noout參數關閉的是什麼輸出呢:)
