在 x node minidom 之后插入 xml python

Insert after x node minidom xml python

我正在将一个节点附加到 xml,但我希望它插入到某些标签之前,这可能吗?

newNode = xmldoc.createElement("tag2")
txt = xmldoc.createTextNode("value2")
newNode.appendChild(txt)
n.appendChild(newNode)

这是我的XML。当我附加 child 时,它会在 UniMed 之后添加,我希望它在 Cantidad 之后和 UniMed 之前插入。 (我的XML的简化版)"Item"可以有更多的child,不知道有多少

<ns0:Item>
      <ns0:Cantidad>1</ns0:Cantidad>
      <ns0:UniMed>L</ns0:UniMed>
</ns0:Item>

我想我可以通过阅读 Item 的所有 child 来解决它,删除它们,然后按我想要的顺序添加它们。 但我认为这不是最好的主意...

有什么想法吗?


已编辑

解决方案

itemChildNodes = n.childNodes
n.insertBefore(newNode, itemChildNodes[itemChildNodes.length-2])

使用insertBefore方法插入新创建的标签。

演示:

>>> from xml.dom import minidom
>>> content = """
... <xml>
...     <Item>
...           <Cantidad>1</Cantidad>
...           <UniMed>L</UniMed>
...     </Item>
... </xml>
... """
>>> root = minidom.parseString(content)
>>> insert_tag = root.createElement("tag2")
>>> htext = root.createTextNode('test')
>>> insert_tag.appendChild(htext)
<DOM Text node "'test'">
>>> 
>>> items = root.getElementsByTagName("Item")
>>> item = items[0]
>>> item_chidren = item.childNodes
>>> item.insertBefore(insert_tag, item_chidren[2])
<DOM Element: tag2 at 0xb700da8c>
>>> root.toxml()
u'<?xml version="1.0" ?><xml>\n\t<Item>\n\t      <Cantidad>1</Cantidad><tag2>test</tag2>\n\t      <UniMed>L</UniMed>\n\t</Item>\n</xml>'
>>>