Python中ElementTree中的同级节点

2024-10-04 09:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在查看一段要添加节点的XML。在

<profile>
    <dog>1</dog>
        <halfdog>0</halfdog>
    <cat>545</cat>
        <lions>0</lions>
    <bird>23</bird>
        <dino>0</dino>
        <pineapples>2</pineapples>
    <people>0</people>
</profile>

有了上面的XML,我可以在其中插入XML节点。但是,我不能插入到确切的位置。在

有没有一种方法可以找到我是否在某个节点的旁边,无论是在它之前还是之后。假设我想在<dino>0</dino><pineapples>2</pineapples>节点之间添加<snail>2</snail>。在

使用ElementTree如何找到我旁边的节点?我问的是ElementTree或任何标准的Python库。不幸的是,lxml对我来说是不可能的。在


Tags: 方法标准节点xmlprofilepeoplecatdog
2条回答

如果知道父元素和要在前面插入的元素,则可以对ElementTree使用以下方法:

index = parentElem.getchildren().index(elemToInsertBefore)
parent.insert(index, newElement)

我相信使用ElementTree是不可行的,但是可以使用标准python minidom

# create snail element
snail = dom.createElement('snail')
snail_text = dom.createTextNode('2')
snail.appendChild(snail_text)

# add it in the right place
profile = dom.getElementsByTagName('profile')[0]
pineapples = dom.getElementsByTagName('pineapples')[0]
profile.insertBefore(snail, pineapples)

输出:

^{pr2}$

相关问题 更多 >