Python minidom:#text 节点在将其附加到新的父节点时消失 [英] Python minidom: #text node disappears when appending it to new parent node
问题描述
我的 XML 如下所示:
<段><词组>child_0</词组>child_1<词组>child_2</词组></示例>
我希望它看起来像这样:
<词组>child_0</词组>child_1<词组>child_2</词组></foo>
很简单吧?我创建了一个新的父节点 --
-- 然后遍历
节点并将子节点附加到新的 节点.foo>
节点.
奇怪的是,当我尝试这样做时 child_1
(一个文本节点)消失了.如果我简单地遍历 <para>
节点,我会得到:
所以有3个子节点,中间一个是文本节点.但是当我尝试将它附加到新的 <foo>
节点时,它没有成功.
@#$%&*!
是怎么回事?
好吧,我在这里回答我自己的问题.
appendChild()
函数从
节点列表中删除子节点,因此您将有效地跳过每个其他元素,因为索引与每次迭代不同步.解决方案是附加节点的副本:
对于 para.childNodes 中的 p:p_copy = p.cloneNode(deep=True)foo_node.appendChild(p_copy)
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?
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)
这篇关于Python minidom:#text 节点在将其附加到新的父节点时消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!