Python XML - 从注释块中的元素访问属性

时间:2018-04-03 09:12:04

标签: python xml

我有一个xml文档,其结构如下:

<persons>   
    <person name="John">
        <personattributes>
            <age>32</age>
        </personattributes>
    </person>
    <!-- <person name="Jane">
        <personattributes>
            <age>25</age>
        </personattributes>
    </person> -->
</persons>

请注意,“Jane”已被注释掉。

如何从这两个元素中访问属性,这样如果我想要一个名字列表,我会得到John和Jane?

我希望能够使用name属性对特定元素进行注释和取消注释,并编写了以下代码,使我能够对特定元素进行注释并取消注释所有节点。

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

如何将“comment_element”中的功能应用于“uncomment_elements”功能?

0 个答案:

没有答案
相关问题