Python XML-从注释块中的元素访问属性
我有一个结构如下的xml文档:Python XML-从注释块中的元素访问属性,python,xml,Python,Xml,我有一个结构如下的xml文档: <persons> <person name="John"> <personattributes> <age>32</age> </personattributes> </person> <!-- <person name="Jane"> <personat
<persons>
<person name="John">
<personattributes>
<age>32</age>
</personattributes>
</person>
<!-- <person name="Jane">
<personattributes>
<age>25</age>
</personattributes>
</person> -->
</persons>
如何将“注释元素”的功能应用于“取消注释元素”功能
import os
import lxml.etree as ET
tree = ET.parse("filepath")
def comment_element(tree, name):
for logger in tree.xpath('//theme'):
if logger.get('name') == name:
logger.getparent().replace(logger, ET.Comment(ET.tostring(logger)))
return tree
def uncomment_elements(tree):
comments = tree.xpath('//comment()')
for c in comments:
p = c.getparent()
p.remove(c)
return tree
with open("outputfile", 'wb') as f:
f.write(ET.tostring(tree, encoding='utf-8'))