如何使用lxml从XML检索xsi:noNamespaceSchemaLocation?

2024-04-19 08:51:34 发布

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

我正在尝试基于xsi:noNamespaceSchemaLocation验证XML

我研究了这个问题,但似乎没有任何可行的解决方案

我的XML文件如下所示:

<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
  <orderperson>John Smith</orderperson>
  <shipto>
    <name>Ola Nordmann</name>
    <address>Langgt 23</address>
    <city>4000 Stavanger</city>
    <country>Norway</country>
  </shipto>
  <item>
    <title>Empire Burlesque</title>
    <note>Special Edition</note>
    <quantity>1</quantity>
    <price>10.90</price>
  </item>
  <item>
    <title>Hide your heart</title>
    <quantity>1</quantity>
    <price>9.90</price>
  </item>
</shiporder>

我从w3school拿的

这是我从根解析和获取attrib时得到的结果 {'{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation': 'shiporder.xsd'}

我如何使用Python中的lxml来实现这一点?我查看了其他解析器,但到目前为止还不知道如何做


Tags: instanceorghttptitlewwwxmlitemprice
1条回答
网友
1楼 · 发布于 2024-04-19 08:51:34

感谢@mzjn指出了克拉克符号

我提出的解决方案是:

from lxml import etree

...

it = etree.fromstring(xml)
# We need to go through all keys since they can be in
# Clark notation and have URL with brackets as a prefix
for attr in it.attrib:
    if 'noNamespaceSchemaLocation' in attr:
        xsd = it.attrib.get(attr)
        break

...

# Do validations based on XSD URL value

相关问题 更多 >