我正在修改一个beauthoulGroup对象,但是附加一个标记似乎并没有实际地将标记附加到任何地方。更改标记的名称确实有效,但由于某些原因,.append不起作用。有人知道我做错了什么吗?我能想到的唯一原因是.append功能不能正常工作,而是在正式文档中创建了一个新副本。在
testclade = """
<phy:clade branch_length_attr="0.00576111248034">
<phy:name>22316-6_AHCVY7AFXX_S13.27</phy:name>
<phy:branch_length>5.761112e-03</phy:branch_length>
</phy:clade>
"""
from bs4 import BeautifulSoup as bs
soup = bs(testclade, 'xml')
clades = soup.find_all('clade')
for c in clades:
if len(c.contents) == 5:
print 'leaf clade detected, changing contents...'
# create a tag to be added
mouseovertag = soup.new_tag('annotation')
# append the mouseovertag to the leaf-clade.
# This apparently does not work, the mouseovertag is nowhere to be seen
c.append(mouseovertag)
# replace the name of the leaf clade. This does work!
c.string = 'the changed name'
print soup.prettify()
如果我认为您想向
clade
xml元素添加一个新的键值对,那么下面的代码就完成了这项工作,尽管感觉很糟糕。在它也会出现在你对
soup.prettify()
的调用中。在查看documentation
.new_tag()
是为了给所选元素添加一个新的xml标记,而不是修改现有的元素。在相关问题 更多 >
编程相关推荐