【问题标题】:How to read commented text from XML file in python如何在python中从XML文件中读取注释文本
【发布时间】:2020-04-19 23:11:50
【问题描述】:

我可以使用“import xml.etree.ElementTree as et”读取 xml 文件。但我的问题是阅读数据文件中给出的commented text,如何阅读: 例如在下面的 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>

【问题讨论】:

  • 检查这个:bugs.python.org/issue8277
  • 感谢您的帮助,但我收到错误消息 - “ImportError: cannot import name 'XMLTreeBuilder' from 'xml.etree.ElementTree” 当我搜索并尝试使用以下代码时:

标签: python xml elementtree


【解决方案1】:

ElementTree 的标准行为是忽略 cmets。但是,可以使用自定义解析器对象保留 cmets。这在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)

输出:

  1997 Cadillac Catera  
  Electrical/Headlight/Switch  

对于旧版本的 Python,需要更多代码。见Faithfully Preserve Comments in Parsed XML

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2012-08-17
    • 2022-01-04
    • 1970-01-01
    • 2019-01-17
    • 2012-10-29
    相关资源
    最近更新 更多