gpt4 book ai didi

python /迷你王国 : Iterate on a NodeList

转载 作者:数据小太阳 更新时间:2023-10-29 02:36:32 25 4
gpt4 key购买 nike

我正在制作一个解析 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/

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