作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我正在制作一个解析 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/
Epic喜加一:免费领取《失忆症:猪猡的机器》《王国:新大陆》 王国:新大陆是一款极简的微型策略游戏,拥有现代复古美学元素和环境音轨。 玩家们会控制一名国王,在游戏中探索世界、招募忠诚的臣民并抵
我是一名优秀的程序员,十分优秀!