[Mac/Linux] 使用 xmllint 檢查 XML 是否符合 schema

[Mac/Linux] 使用 xmllint 檢查 XML 是否符合 schema

最近同事分享了一個 xmllint 的命令列工具,

可以在 Mac/Linux 上檢查 XML 是否符合 schema,

這邊也來分享一下吧~

 

xmllint 是屬於 libxml2 這個套件之內的,

所以一般正常安裝的 Mac/Linux 應該都可以直接使用了~

沒有的話就再自己去找編譯安裝的方式吧 (指)~

 

W3School 的 XML 來當個範例:

<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

 

假設它的 schema 是像這樣:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

 

要用 xmllint 檢查 schema 時,只要下 xmllint –schema <schema file> <xml file> 就行了,

成功的話就可以看到某某檔案 validates:

testuser@localhost ~ $ xmllint --schema test_schema.xsd test.xml
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
test.xml validates

 

若是不符合 schema 的話,xmllint 也會指出來錯誤在哪裡~

像是我把 xml 裡的 heading 和 body 調換位置的話,

xmllint 就指出了 body 出現在不預期的位置上,預期的是 heading:

testuser@localhost ~ $ xmllint --schema test_schema.xsd test_bad.xml
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
<heading>Reminder</heading>
</note>
test.xml:5: element body: Schemas validity error : Element 'body': This element is not expected. Expected is ( heading ).
test.xml fails to validate

 

可以用這個簡單的小工具快速檢查 XML 是否符合 schema 囉~

(本頁面已被瀏覽過 644 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料