解析XSD文件失败 -> 找不到任何标签

0 投票
2 回答
725 浏览
提问于 2025-04-18 09:42

我现在正在用Python的lxml库解析一个XSD文件。为了测试,我复制了以下文件:

<xs:schema targetNamespace="http://www.w3schools.com" elementFormDefault="qualified">  
  <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:simpleType name="BaselineShiftValueType">
  <xs:annotation>
    <xs:documentation>The actual definition is
            baseline | sub | super | <percentage> | <length> | inherit 
            not sure that union can do this 
    </xs:documentation>
  </xs:annotation>
  <xs:restriction base="string"/>
 </xs:simpleType>
</xs:schema>

现在我想获取根节点(schema)的子节点,也就是:xs:element和xs:simpleType。通过遍历根节点的子节点,一切都正常:

root = self.XMLTree.getroot()
for child in root:
    print("{}: {}".format(child.tag, child.attrib))

这会输出:

{http://www.w3.org/2001/XMLSchema}element: {'name': 'note'}
{http://www.w3.org/2001/XMLSchema}simpleType: {'name': 'BaselineShiftValueType'}

但是当我想只获取某种类型的子节点时,就不行了:

root = self.XMLTree.getroot()
element = self.XMLTree.find("element")
print(str(element))

这给我的输出是:

None

而且使用findall或者写./element.//element也没有改变结果。我很确定我漏掉了什么。正确的方法是什么呢?

2 个回答

0

为了跟随 @helderdarocha的回答,你还可以在一个字典里定义你的命名空间,然后像在 python xml.etree.ElementTree 文档 中那样,在你的搜索函数中使用它:

ns = {'xs',"http://www.w3.org/2001/XMLSchema"}
element = self.XMLTree.find("element", ns)
1

你缺少了命名空间。没有前缀的XPath选择器被认为不属于任何命名空间。你需要用register_namespace来注册它:

self.XMLTree.register_namespace('xs',"http://www.w3.org/2001/XMLSchema")

然后使用带前缀的选择器来找到你的元素:

element = self.XMLTree.find("xs:element")

撰写回答