How to read commented text from XML file in python

China☆狼群 提交于 2021-02-04 08:33:10

问题


I am able to read the xml file in a using 'import xml.etree.ElementTree as et'. But my problem is to read the commented text given in the data file, how to read this: For example in the below xml, I want to read BaseVehicle is 1997 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>

回答1:


The standard behaviour of ElementTree is to ignore comments. However, comments can be preserved by using a custom parser object. This has become easier in Python 3.8, where the xml.etree.ElementTree.TreeBuilder target can be configured to process comment events in order to include them in the generated tree.

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 Cadillac Catera  
  Electrical/Headlight/Switch  

With older versions of Python, some more code is needed. See Faithfully Preserve Comments in Parsed XML.



来源:https://stackoverflow.com/questions/59543824/how-to-read-commented-text-from-xml-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!