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

2023-12-25

我可以使用“import xml.etree.ElementTree as et”读取 xml 文件。但我的问题是阅读评论文本数据文件中给出,如何读取: 例如在下面的 xml 中,我想阅读基础车辆 is 1997 凯迪拉克卡特拉

<App action="A" id="1">
    <BaseVehicle id="8559"/>
    <!--  1997 Cadillac Catera  -->
    <Qty>1</Qty>
    <PartType id="4472"/>
    <!--  Electrical/Headlight/Switch  -->
    <Part>SW1406</Part>
</App>

ElementTree 的标准行为是忽略注释。但是,可以通过使用自定义解析器对象来保留注释。这变得更容易Python 3.8 https://docs.python.org/3/whatsnew/3.8.html#xml,其中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)

Output:

1997 凯迪拉克卡特拉
电气/头灯/开关

对于旧版本的 Python,需要更多代码。看忠实地保留已解析 XML 中的注释 https://stackoverflow.com/q/33573807/407651.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中从XML文件中读取注释文本 的相关文章

随机推荐