我有一个XML元素,在该元素下有注释。有没有办法用lxml删除注释?
<TEST name="1">
<!-- test values: 1, 2, 3-->
<file name="test1.py" />
</TEST >
<RESULT name="r1" value="false">
<!-- result values: true, false-->
</RESULT >
我想将元素“TEST”下的注释更改为:
<TEST name="1">
<!-- test values: 1, 2, 3, 4, 5-->
<file name="test1.py" />
</TEST >
<RESULT name="r1" value="false">
<!-- result values: true, false-->
</RESULT >
由于
答案 0 :(得分:0)
<field name="Payload" type="text_general" indexed="true" stored="true"/>
出:
from lxml import etree
html = '''
<root>
<TEST name="1">
<!-- test values: 1, 2, 3-->
<file name="test1.py" />
</TEST >
<RESULT name="r1" value="false">
<!-- result values: true, false-->
</RESULT >
</root>'''
r = etree.fromstring(html)
comments = r.xpath(r'//comment()')
for c in comments:
p = c.getparent()
p.remove(c)
print (etree.tostring(r))
答案 1 :(得分:0)
import lxml.etree as et
xml = '''
<head>
<TEST name="1">
<!-- test values: 1, 2, 3-->
<file name="test1.py" />
</TEST >
<RESULT name="r1" value="false">
<!-- result values: true, false-->
</RESULT >
</head>
'''
tree=et.fromstring(xml)
for bad in tree.xpath("//head/TEST/comment()"):
bad.text += ', 4, 5'
print(et.tostring(tree, pretty_print=True))