”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在 Python 中使用 ElementTree 的“find”和“findall”方法时如何忽略 XML 命名空间?

在 Python 中使用 ElementTree 的“find”和“findall”方法时如何忽略 XML 命名空间?

发布于2024-11-08
浏览:213

How to Ignore XML Namespaces when Using ElementTree\'s \

在 ElementTree 的“find”和“findall”方法中忽略 XML 命名空间

使用 ElementTree 模块解析和定位 XML 文档中的元素时,命名空间会带来复杂性。下面介绍了如何在 Python 中使用“find”和“findall”方法时忽略命名空间。

当 XML 文档包含命名空间时,会导致 ElementTree 模块在搜索标签时考虑它们,就会出现问题。这可能会导致意外结果,如问题中提供的示例所示:

el1 = tree.findall("DEAL_LEVEL/PAID_OFF")  # Return None
el2 = tree.findall("{http://www.test.com}DEAL_LEVEL/{http://www.test.com}PAID_OFF")  # Return element

要忽略命名空间,解决办法是在使用“find”或“findall”方法之前修改已解析的XML文档中的标签。这可以使用 ElementTree 的 iterparse() 方法来实现:

import io
from xml.etree import ElementTree as ET

# Parse the XML document
it = ET.iterparse(StringIO(xml))

# Iterate over each element and strip the namespace if present
for _, el in it:
    _, _, el.tag = el.tag.rpartition("}")  # strip ns

# Get the modified root element
root = it.root

# Now, you can search for elements without namespaces
el3 = root.findall("DEAL_LEVEL/PAID_OFF")  # Return matching elements

这个解决方案修改了解析文档中的标签,使得更容易定位元素,而不需要手动为每个标签指定命名空间前缀。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3