我有以下xml:
<text>test<br/><br/><a href="/nature/19700707">All you need to know about British birds.</a><br/></text>
我希望将代码<text>
的全部内容设置为11111
我正在使用pythong和lxml,以下是我的代码:
import nltk
import lxml.etree as le
current_file = '/Users/noor/Dropbox/apps/APIofLife/src/clear_description/bird.rdf'
f = open(current_file,'r')
doc=le.parse(f)
for elem in doc.xpath("//text"):
elem.text = "11111"
f.close()
f = open(current_file,'w')
f.write(le.tostring(doc))
f.close()
但是,运行上述代码后,我的结果是:
<text>11111<br/><br/><a href="/nature/19700707">All you need to know about British birds.</a><br/></text>
我想知道为什么标记<text>
的所有内容都没有更改为11111
答案 0 :(得分:1)
根据lxml.etree._Element
documentation,text
属性对应于第一个子元素之前的文本。
您需要删除子元素:
>>> import lxml.etree as le
>>>
>>> root = le.fromstring('''<text>test<br/><br/>
... <a href="/nature/19700707">All you need to know about British birds.</a>
... <br/></text>''')
>>> for elem in root.xpath("//text"):
... elem.text = '1111'
... del elem[:] # <----------
...
>>> le.tostring(root)
'<text>1111</text>'