问题
I have XML that looks like this:
<example>
<para>
<phrase>child_0</phrase>
child_1
<phrase>child_2</phrase>
</para>
</example>
and I want it to look like this:
<foo>
<phrase>child_0</phrase>
child_1
<phrase>child_2</phrase>
</foo>
Simple, right? I create a new parent node -- <foo>
-- and then iterate through the <para>
node and append the children to the new <foo>
node.
What's strange is that the child_1
(a text node) disappears when I try to do so. If I simply iterate through the <para>
node, I get this:
>>> for p in para.childNodes:
print p.nodeType
1
3
1
So there are 3 child nodes, and the middle one is the text node. But when I try to append it to the new <foo>
node, it doesn't make it.
>>> for p in para.childNodes:
foo_node.appendChild(p)
>>> print foo_node.toprettyxml()
<foo>
<phrase>child_0</phrase>
<phrase>child_2</phrase>
</foo>
What the @#$%&*!
is going on?
回答1:
Well, here I am, answering my own question.
The appendChild()
function removes the child node from the <para>
list of nodes, so you will be effectively skipping every other element as the index gets out of sync with each iteration. The solution is to append a copy of the node:
for p in para.childNodes:
p_copy = p.cloneNode(deep=True)
foo_node.appendChild(p_copy)
来源:https://stackoverflow.com/questions/38859341/python-minidom-text-node-disappears-when-appending-it-to-new-parent-node