我遇到了使用lxml库在 python 中创建 xsd 模式的问题。我在下面准备了一个 xsd 架构文件(内容被削减到最低限度)
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="qualified"
version="2.4">
<xs:annotation>
<xs:documentation xml:lang="de">Bundeseinheitlicher Medikationsplan</xs:documentation>
</xs:annotation>
<xs:element name="MP">
<xs:annotation>
<xs:documentation>Bundeseinheitlicher Medikationsplan</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:attribute name="p" use="prohibited">
<xs:annotation>
<xs:documentation>Name: Patchnummer</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:int">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="99"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>
Run Code Online (Sandbox Code Playgroud)
以及使用lxml库创建这样的 xsd 架构时
from lxml import etree
with open('some_file.xsd') as schema_file: # some_file.xsd is the file above
etree.XMLSchema(file=schema_file)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "src/lxml/xmlschema.pxi", line 87, in lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:197804)
lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}attribute': The content is not valid. Expected is (annotation?)., line 16
Run Code Online (Sandbox Code Playgroud)
但是当使用 python 标准库执行此操作时,一切正常
import xml.etree.ElementTree as ET
with open('some_file.xsd') as f:
tree = ET.parse(f)
Run Code Online (Sandbox Code Playgroud)
我玩了一下 xsd 文件,发现use="prohibited"从属性元素中删除时
可以解决lxml库的问题,但我需要该属性。
原因是什么?是lxml库有问题还是上面 xsd 的 xml 结构不正确?
这个问题很老了,但让我有点困惑。
我是这样解决的。
schema_root = etree.parse(xsd_filename)
schema = etree.XMLSchema(schema_root)
xml_parser = etree.XMLParser(schema=schema, no_network=False)
Run Code Online (Sandbox Code Playgroud)
然后如果你尝试用类似的东西打开它
with open(xml_filename, 'rb') as f:
etree.fromstring(f.read(), xml_parser)
Run Code Online (Sandbox Code Playgroud)
你只会得到实际的XMLSchemaErrors
https://lxml.de/api/lxml.etree.XMLParser-class.html