简体   繁体   English

如何让 Python 的 ElementTree 强制执行 XML 模式?

[英]How can I make Python's ElementTree enforce XML schema?

Suppose I wish to parse an XML document, and its schema dictates that a given element can only occur once.假设我想解析一个 XML 文档,它的模式规定给定的元素只能出现一次。

How do I make sure that an exception gets raised if the element occurs twice or more?如果元素出现两次或更多次,如何确保引发异常?

Or, if the schema says that a given element's value should be an integer, and the value is "turkey sandwich", how do I make the parser crash and burn like it's supposed to?或者,如果模式说给定元素的值应该是一个整数,而该值是“火鸡三明治”,我该如何让解析器像预期的那样崩溃和燃烧?

Can ElementTree do this? ElementTree 可以做到这一点吗? Can anything do this?有什么可以做到这一点吗? Does this question even make sense?这个问题还有意义吗?

ElementTree from the STD lib has not schema support. STD 库中的 ElementTree 不支持模式。 For this, I suggest you to use the lxml package which has it (and by the way, it's much faster).为此,我建议您使用包含它的lxml包(顺便说一下,它要快得多)。

Here after an example from my own code:在我自己的代码示例之后:

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)

or if you want a exception to be raised:或者如果您想引发异常:

xmlschema.assertValid(doc)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将xml元素转换为ElementTree(python)? - How can I turn an xml Element into an ElementTree (python)? 如何使用 python 中的 Elementtree 创建一个循环,为 XML 提供唯一值作为 output 的循环? - How do I make a loop that gives unique values as output for XML with Elementtree in python? 如何在不移动命名空间的情况下使用Python的ElementTree解析和编写XML? - How do I parse and write XML using Python's ElementTree without moving namespaces around? 如何让 Python 的 ElementTree 漂亮地打印到 XML 文件? - How do I get Python's ElementTree to pretty print to an XML file? 如何使用ElementTree在python中制作xml树的副本? - How to make a copy of xml tree in python using ElementTree? 如何使用Python和ElementTree从XML文件的所有元素中提取所有内容? - How can I extract all content from all elements of an XML file with Python and ElementTree? 如何使用 Python ElementTree 从 XML 文件中的不同子级元素中提取相关属性 - how can I extract related attributes from different child level elements from XML file with Python ElementTree 如何将一个全新的元素(在 Python 中使用 ElementTree)添加到 XML 文件 - How can i add a full new Element (using ElementTree in Python) to a XML File 如何在python中使用ElementTree输出XML文件? - How do I output an XML file using ElementTree in python? 我如何使用QName(python xml.etree.ElementTree?) - How do I use QName (python xml.etree.ElementTree?)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM