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

3 投票
1 回答
5314 浏览
提问于 2025-04-18 13:11

假设我想解析一个XML文档,而它的结构规定某个元素只能出现一次。

我该怎么做才能确保如果这个元素出现两次或更多次,就会抛出一个异常呢?

或者,如果结构规定某个元素的值应该是一个整数,但实际值却是“火鸡三明治”,我该怎么让解析器像应该的那样崩溃呢?

ElementTree能做到这一点吗?有没有其他工具可以做到?这个问题有意义吗?

1 个回答

8

标准库里的ElementTree不支持模式(schema)。为了这个功能,我建议你使用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)

撰写回答