如何在Python中从XML文件中读取注释文本

KD0*_*D01 2 python xml elementtree

我可以使用“import xml.etree.ElementTree as et”读取 xml 文件。但我的问题是读取数据文件中给出的注释文本,如何读取:例如在下面的 xml 中,我想读取BaseVehicle1997 Cadillac Catera

<App action="A" id="1">
    <BaseVehicle id="8559"/>
    <!--  1997 Cadillac Catera  -->
    <Qty>1</Qty>
    <PartType id="4472"/>
    <!--  Electrical/Headlight/Switch  -->
    <Part>SW1406</Part>
</App>
Run Code Online (Sandbox Code Playgroud)

mzj*_*zjn 8

ElementTree 的标准行为是忽略注释。但是,可以通过使用自定义解析器对象来保留注释。这在Python 3.8中变得更加容易,其中xml.etree.ElementTree.TreeBuilder可以将目标配置为处理评论事件,以便将它们包含在生成的树中。

from xml.etree import ElementTree as ET

parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)) # Python 3.8
tree = ET.parse("app.xml", parser)

# Get the comment nodes
for node in tree.iter():
    if "function Comment" in str(node.tag): 
        print(node.text)
Run Code Online (Sandbox Code Playgroud)

输出:

1997 凯迪拉克 Catera
电气/车头灯/开关

对于旧版本的 Python,需要更多代码。请参阅在解析的 XML 中忠实地保留注释