Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python XML-从注释块中的元素访问属性_Python_Xml - Fatal编程技术网

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

Python XML-从注释块中的元素访问属性,python,xml,Python,Xml,我有一个结构如下的xml文档: <persons> <person name="John"> <personattributes> <age>32</age> </personattributes> </person> <!-- <person name="Jane"> <personat

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

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