python /迷你王国 : Iterate on a NodeList

标签 python xml minidom

我正在制作一个解析 XML 文件的 Python 程序。我需要遍历 NodeList,但我在使用“for node in NodeList”语法时遇到了问题。

这是一个代码示例:

docToInclude = parse(node.getAttribute("file"))

print ("childNode count : " , len(docToInclude.documentElement.childNodes))
print ("childNodes : " , docToInclude.documentElement.childNodes)
print("")

for i in range(0, len(docToInclude.documentElement.childNodes)):
    print ("i  = ", i , "nodeName = " + docToInclude.documentElement.childNodes[i].nodeName)

print("")

for elementNode in docToInclude.documentElement.childNodes :
    print ("node name : " ,  elementNode.nodeName)
    node.parentNode.insertBefore(elementNode, insertPosition)

这是输出:

childNode count :  3
childNodes :  [<DOM Text node "'\n\n\t'">, <DOM Element: messageList at 0x3a4e570>, <DOM Text node "'\n\n'">]

i  =  0 nodeName = #text
i  =  1 nodeName = messageList
i  =  2 nodeName = #text

node name :  #text
node name :  #text

如果我在 NodeList 语法中使用 for 节点进行迭代,则会跳过一个元素。 你知道这个问题的根源吗?

最佳答案

您在遍历元素时将元素移出 childNodes。这更改 childNodes 列表:

>>> lst = [1, 2, 3]
>>> for i, elem in enumerate(lst):
...    print i, elem
...    del lst[i]
...    
0 1
1 3

您将不得不迭代列表的副本;在这里,我使用 [:] 切片符号创建列表的副本:

for elementNode in docToInclude.documentElement.childNodes[:]:
    print ("node name : " ,  elementNode.nodeName)
    node.parentNode.insertBefore(elementNode, insertPosition) 

帮自己一个大忙,使用 ElementTree API反而;该 API 远比 XML DOM API 更 pythononic 且更易于使用:

from xml.etree import ElementTree as ET

etree = ET.fromstring(data)
for element in etree.findall('messageList'):
    print element

关于 python /迷你王国 : Iterate on a NodeList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12510112/

相关文章:

python - Pandas :计算数字并结合应用的结果

python - flask 记录根本不起作用

python - 将 Selenium Webdriver 元素数组转换为它们的值?

javascript - 在没有页面刷新的情况下提交表单不起作用

java - 从应用程序内永久添加按钮

java - 确定基于 XML 文件的类型以指定相应的处理程序

Python ElementTree xml 内容作为字符串

python字符串解析不解析换行符

python - 无法使用 cx_Oracle 写入 Unicode 文本

python - 使用 Python 以 minidom 获取元素值