【发布时间】:2021-12-08 22:03:48
【问题描述】:
我当前的任务是从 XSD 文件中获取信息(字段类型、字段名称等)。我的 XSD 文件看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2018 rel. 2 sp1 (x64) (http://www.altova.com) by test (123321) -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:complexType name="attribute">
<xs:annotation>
<xs:documentation>Атрибуты ОГХ</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="owner_id">
<xs:annotation>
<xs:documentation>Данные о балансодержателе</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="legal_person" type="xs:integer">
<xs:annotation>
<xs:documentation>ID балансодержателя</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="snow_clean_area" type="xs:double">
<xs:annotation>
<xs:documentation>Площадь вывоза снега, кв. м</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>
如我们所见,有一些字段
我需要获取该 XSD 中所有元素的名称。但是如果一个元素在另一个元素中,我需要将名称写为“all_prev_names;cur_name”。对于我之前展示的 XSD,它将是:
"owner_id;legal_person"
"snow_clean_area"
要进行更多嵌套,名称必须包含所有以前的名称。
我写了那个代码:
def recursive(xml, name=None):
res = xml.find_all('xs:element')
if res:
for elem in res:
if name:
yield from recursive(elem, elem['name'] + ';' + name)
else:
yield from recursive(elem, elem['name'])
else:
if name:
yield (name)
else:
yield (xml['name'])
但是重复路径存在问题。该函数的结果将是:
"owner_id;legal_person"
"legal_person"
"snow_clean_area"
我需要修复该代码,或者获得另一个想法,如何解决该任务。
【问题讨论】:
-
您可以尝试使用xml2xpath.sh 从xsd 生成一个xml 并获取XPath 表达式:
xml2xpath.sh -a -f shiporder -d tests/resources/shiporder.xsd。需要xmlbeans 包。
标签: python xml beautifulsoup xsd