首页  >  文章  >  后端开发  >  如何在 Python ElementTree 中忽略元素位置的 XML 命名空间?

如何在 Python ElementTree 中忽略元素位置的 XML 命名空间?

Linda Hamilton
Linda Hamilton原创
2024-10-26 07:18:30512浏览

How to Ignore XML Namespaces for Element Location in Python ElementTree?

在 Python ElementTree 中忽略元素位置的 XML 命名空间

在 ElementTree 模块中,在遇到以下情况时,在 XML 文件中定位特定元素可能具有挑战性命名空间,如提供的示例所示。使用findall方法时,在每个标签前包含{http://www.test.com}会变得不方便。

解决方案:

而不是修改对于 XML 文档本身,更优化的方法是在解析 XML 后修改标签名称。这允许处理多个命名空间和命名空间别名。

这是使用 iterparse 函数修改的代码:

<code class="python">from io import StringIO  # for Python 2 import from StringIO instead
import xml.etree.ElementTree as ET

with open('test.xml', 'r') as f:
    xml = f.read()

it = ET.iterparse(StringIO(xml))
for _, el in it:
    _, _, el.tag = el.tag.rpartition('}')  # strip ns

root = it.root</code>

通过设置 _, _, el.tag = el.tag。 rpartition('}'),命名空间 (_{http://www.test.com}) 从标签名称中删除。这允许对标签进行后续处理,而无需考虑其名称空间。因此,findall 方法:

<code class="python">el1 = root.findall("DEAL_LEVEL/PAID_OFF")</code>

将返回所需的 。不带命名空间前缀的元素。

以上是如何在 Python ElementTree 中忽略元素位置的 XML 命名空间?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn