解析XSD文件以获取名称和描述

2024-05-23 22:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解析这个XSD文件,目前正在python中尝试,以获取元素的名称和数据的描述。在

示例XSD:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" version="07112016">
    <xs:annotation>
        <xs:documentation>Level 1: top level of Procurement Data Standard for a procurement instrument document.</xs:documentation>
    </xs:annotation>
    <xs:element name="ProcurementDocument">
        <xs:annotation>
            <xs:documentation>The root element for any procurement instrument document</xs:documentation>

这里它将抓取name: ProcurementDocument和{}。在

here是我试图使用正则表达式提取的更多数据。当我把它全部放在一行上,但仍然没有提取每个实例时,我获得了更大的成功。在

这是我的完整代码,我试图用它从我的缩小的XSD中获取所有的案例,但是在我试图找到的1500个案例中,只找到了~120个。在

^{pr2}$

Tags: 文件数据name元素fordocumentationannotationelement
1条回答
网友
1楼 · 发布于 2024-05-23 22:42:11

您应该避免使用regex解析xml/html/json,因为regex没有足够的能力解析嵌套结构。在

regex不能捕获文本中所有name和description实例的原因是,您选择的用于捕获描述[\w\s\.]+的字符集不够,因为在description中存在诸如括号(see list)这样的字符,这将导致进一步的匹配失败。尝试将[\w\s\.]+更改为.+?,然后它就可以工作了。检查下面更新的regex101演示链接。在

Working Demo of your modified regex

编辑:演示如何使用Beautiful Soup解析xml以获取所需信息的示例示例

import re
from bs4 import BeautifulSoup

data = '''<xs:element name="ProductDescription"><xs:annotation><xs:documentation>Provides the description of the product</xs:documentation></xs:annotation><xs:complexType><xs:sequence><xs:element name="ProductName"><xs:annotation><xs:documentation>Provides a name for the product. (see list)</xs:documentation></xs:annotation><xs:simpleType><xs:restriction base="xs:token"><xs:enumeration value="Barbie Doll"/><xs:enumeration value="Ken Doll"/></xs:restriction></xs:simpleType></xs:element><xs:element name="ProductSize"><xs:annotation><xs:documentation>Describes the size of the product. (see list)</xs:documentation></xs:annotation><xs:simpleType><xs:restriction base="xs:token"><xs:enumeration value="Small"/><xs:enumeration value="Medium"/><xs:enumeration value="Large"/><xs:enumeration value="Dayum"/></xs:restriction></xs:simpleType></xs:element></xs:sequence></xs:complexType></xs:element>'''

soup = BeautifulSoup(data)

for element in soup.find_all('xs:element'):
 print(element['name'])  # prints name attribute value
 print(element.find('xs:documentation').get_text(),'\n')  # prints inner text of xs:documentation tag

打印你想要的名字和描述

^{pr2}$

相关问题 更多 >