[英]How can I make Python's ElementTree enforce XML schema?
假設我想解析一個 XML 文檔,它的模式規定給定的元素只能出現一次。
如果元素出現兩次或更多次,如何確保引發異常?
或者,如果模式說給定元素的值應該是一個整數,而該值是“火雞三明治”,我該如何讓解析器像預期的那樣崩潰和燃燒?
ElementTree 可以做到這一點嗎? 有什么可以做到這一點嗎? 這個問題還有意義嗎?
STD 庫中的 ElementTree 不支持模式。 為此,我建議您使用包含它的lxml包(順便說一下,它要快得多)。
在我自己的代碼示例之后:
from lxml import etree
# Create the schema object
with open(xsd_file) as f:
xmlschema_doc = etree.parse(f)
xmlschema = etree.XMLSchema(xmlschema_doc)
# Create a tree for the XML document
doc = etree.parse(xml_text)
# Validate the XML document using the schema
return xmlschema.validate(doc)
或者如果您想引發異常:
xmlschema.assertValid(doc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.