4

I'm making a Python program that parse XML files. I need to iterate over NodeList, but I have an issue doing it with the "for node in NodeList" syntax.

Here is a sample of code :

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)

Here is the output :

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

If I iterate with the for node in NodeList syntax, an element is skipped. Do you have any idea of this problem origin ?

4

2 に答える 2

2

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
于 2012-09-20T10:01:02.150 に答える
0

appendChild()は次のことを行います。 ここに画像の説明を入力してください

私はコードからそれを学ぶだけです。tuple()を使用するとうまくいくかもしれません。

于 2012-12-20T12:38:18.387 に答える