我正在查看一段 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 节点插入其中。但是,我无法将它插入到确切位置。
有没有办法找到我是否在某个节点旁边,无论是之前还是之后。假设我想添加 <snail>2</snail>
在 <dino>0</dino>
之间和 <pineapples>2</pineapples>
节点。
使用 ElementTree
我怎样才能找到我旁边的节点?我问的是 ElementTree
或任何标准的 Python 库。不幸的是,lxml
这对我来说是不可能的。
最佳答案
我认为使用 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)
输出:
<?xml version="1.0" ?><profile>
<dog>1</dog>
<halfdog>0</halfdog>
<cat>545</cat>
<lions>0</lions>
<bird>23</bird>
<dino>0</dino>
<snail>2</snail><pineapples>2</pineapples>
<people>0</people>
</profile>
关于python - Python 中 ElementTree 中的兄弟节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21178266/