【问题标题】:Remove all comments in Python 3 lxml删除 Python 3 lxml 中的所有注释
【发布时间】:2017-09-27 15:16:41
【问题描述】:

我有一个 XML 文件,之前我注释了一些元素,现在我想取消注释它们..

我有这个结构

<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>

我想取消注释该文件的所有 cmets。因此,注释元素也是如此,我将取消注释它们。

我能够找到使用 xpath 进行注释的元素。这是我的 sn-p 代码。

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)

但是,替换无法正常工作,因为它需要另一个元素。

我该如何解决这个问题?

【问题讨论】:

    标签: python python-3.x xpath lxml


    【解决方案1】:

    您的代码缺少从注释文本创建新 XML 元素的关键部分。还有一些其他错误与不正确的 XPath 查询相关,以及在循环内多次保存输出文件。

    此外,您似乎将xml.etreelxml.etree 混合在一起。根据documentation,前者在解析XML文件时会忽略cmets,所以最好的方法是使用lxml

    在解决了以上所有问题后,我们得到了这样的东西。

    import lxml.etree as ET
    
    
    def unhide_element():
        path = r'test.xml'
        root = ET.parse(path)
        comments = root.xpath('//comment()')
        for c in comments:
            print('Comment: ', c)
            parent_comment = c.getparent()
            parent_comment.remove(c)  # skip this if you want to retain the comment
            new_elem = ET.XML(c.text)  # this bit creates the new element from comment text
            parent_comment.addnext(new_elem)
    
        root.write(r'new_file.xml')
    

    【讨论】:

    • 很好,这很有效。但是,我不知道为什么我的 lxml 版本不首先使用 getroot() 就不能工作。我无法通过解析直接在 ElementTree 中工作。
    【解决方案2】:

    好吧,既然你想取消所有的注释,你真正需要做的就是删除每个“”:

    import re
    
    new_xml = ''.join(re.split('<!--|-->', xml))
    

    或者:

    new_xml = xml.replace('<!--', '').replace('-->', '')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 2019-07-04
      • 2016-05-21
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      相关资源
      最近更新 更多