You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的xml.etree.ElementTree提取XML的Schema位置?

XML Schema位置提取问题解答

问题背景

给定XML根元素:

<shiporder orderid="889923" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="data.xsd">

使用xml.etree.ElementTree解析后,根元素属性输出为:

{'orderid': '889923', '{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation': 'data.xsd'}

需要解决两个问题:

  1. 如何不依赖xsi前缀获取Schema位置?
  2. 若无法实现,提取Schema位置的正确方法是什么?

解答

1. 不依赖xsi前缀获取Schema位置的方法

可以通过命名空间URI直接匹配属性,完全不依赖前缀(前缀只是命名空间的别名,可能在不同XML中变化,但URI是固定的)。

具体实现代码:

import xml.etree.ElementTree as et

# 固定的XMLSchema-instance命名空间URI
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
# 构造带命名空间的属性名
schema_attr_name = f"{{{XSI_NS}}}noNamespaceSchemaLocation"

et_data = et.parse("data.xml")
root = et_data.getroot()

# 通过属性名直接获取Schema路径
xsd_path = root.attrib.get(schema_attr_name)
if xsd_path:
    # 提取文件名部分
    print(xsd_path.split("/")[-1])

这种方法的核心是利用命名空间的唯一标识URI,无论XML里用的前缀是xsi还是其他自定义名称,都能精准匹配目标属性。

2. 备选提取方法(极端场景下)

如果出于特殊限制无法使用命名空间URI,也可以遍历所有属性,通过属性名后缀匹配:

import xml.etree.ElementTree as et

et_data = et.parse("data.xml")
root = et_data.getroot()

xsd_path = None
for attr_name, value in root.attrib.items():
    if attr_name.endswith("noNamespaceSchemaLocation"):
        xsd_path = value
        break

if xsd_path:
    print(xsd_path.split("/")[-1])

但这种方法存在误匹配风险:若其他命名空间下存在同名属性,会提取错误结果,因此优先推荐第一种基于命名空间URI的方法。


内容的提问来源于stack exchange,提问作者Itération 122442

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:10:33