【问题标题】:Insert after x node minidom xml python在 x 节点 minidom xml python 之后插入
【发布时间】:2015-04-07 12:57:37
【问题描述】:

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

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

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

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

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

有什么想法吗?


已编辑

解决方案

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

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    使用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>'
    >>> 
    

    【讨论】:

    • 感谢您的回答。请再看一下我的问题,我编辑了。您的答案有效,但我不知道将其插入到哪个位置。有没有办法知道 childNodes 的长度?喜欢 childNodes.count?
    • 谢谢,它成功了。只是添加了一行以使其更通用。
    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多