我有我以前评论的一些元素一个XML文件中的所有意见,现在我想以取消他们..删除在Python 3 lxml的
我有这样的结构
<parent parId="22" attr="Alpha">
<!--<reg regId="1">
<cont>There is some content</cont><cont2 attr1="val">Another content</cont2>
</reg>
--></parent>
<parent parId="23" attr="Alpha">
<reg regId="1">
<cont>There is more content</cont><cont2 attr1="noval">Morecont</cont2>
</reg>
</parent>
<parent parId="24" attr="Alpha">
<!--<reg regId="1">
<cont>There is some content</cont><cont2 attr1="val">Another content</cont2>
</reg>
--></parent>
我想取消注释文件的所有评论。因此,也是评论的因素,我会取消注释。
我能找到的评论使用XPath的元素。这是我的代码片段。
def unhide_element():
path = r'path_to_file\file.xml'
xml_parser = et.parse(path)
comments = root.xpath('//comment')
for c in comments:
print('Comment: ', c)
parent_comment = c.getparent()
parent_comment.replace(c,'')
tree = et.ElementTree(root)
tree.write(new_file)
但是,替换不工作,因为它期望另一个元素。
我该如何解决这个问题?
大,这个工作。但是,我不知道为什么我的lxml版本不使用getroot()第一次不起作用。我无法直接在ElementTree中解析。 – TMikonos