python3 ElementTree 如何生成文件时「保留注释」?

图1最终输出图2,希望图2包含注释
python3 ElementTree 如何生成文件时「保留注释」?

python3 ElementTree 如何生成文件时「保留注释」?

import xml.etree.ElementTree as ET

if __name__ == '__main__':

xmlPath: str = "2.xml"

parser = ET.XMLParser()

tree = ET.parse(xmlPath, parser=parser)

root = tree.getroot()

for child in root.findall("Project"):

attr = child.attrib

tag = child.tag

if tag == "Project":

root.remove(child)

tree.write("1.xml",encoding='utf8',xml_declaration=True)

<?xml version="1.0" encoding="UTF-8"?>

<!--

sss

-->

<entity-engine-xml date="1664807134203">

<!--

sss

-->

</entity-engine-xml>


回答:

对于代码问题,我的一贯主张是:不解释,直接上代码。

parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))

以上是 python3 ElementTree 如何生成文件时「保留注释」? 的全部内容, 来源链接: utcz.com/p/938636.html

回到顶部