gpt4 book ai didi

Python ElementTree 模块 : How to ignore the namespace of XML files to locate matching element when using the method "find", "findall"

转载 作者:IT老高 更新时间:2023-10-28 21:05:50 26 4
gpt4 key购买 nike

我想用findall的方法在ElementTree模块中定位到源xml文件的一些元素。

但是,源 xml 文件 (test.xml) 具有命名空间。我将 xml 文件的一部分截断为示例:

<?xml version="1.0" encoding="iso-8859-1"?>
<XML_HEADER xmlns="http://www.test.com">
<TYPE>Updates</TYPE>
<DATE>9/26/2012 10:30:34 AM</DATE>
<COPYRIGHT_NOTICE>All Rights Reserved.</COPYRIGHT_NOTICE>
<LICENSE>newlicense.htm</LICENSE>
<DEAL_LEVEL>
<PAID_OFF>N</PAID_OFF>
</DEAL_LEVEL>
</XML_HEADER>

示例python代码如下:

from xml.etree import ElementTree as ET
tree = ET.parse(r"test.xml")
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 '{http://www.test.com}DEAL_LEVEL/PAID_OFF' at 0xb78b90>

虽然使用 "{http://www.test.com}" 有效,但在每个标签前添加命名空间非常不方便。

如何在使用 findfindall、...等函数时忽略命名空间?

最佳答案

与其修改 XML 文档本身,不如先对其进行解析,然后修改结果中的标签。这样你就可以处理多个命名空间和命名空间别名:

from io import StringIO  # for Python 2 import from StringIO instead
import xml.etree.ElementTree as ET

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

这是基于讨论 here .

关于Python ElementTree 模块 : How to ignore the namespace of XML files to locate matching element when using the method "find", "findall",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13412496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com