How to read the content of an XML file in Python?
In Python, you can use the xml.etree.ElementTree module to read and parse XML files. Here is a simple example code:
import xml.etree.ElementTree as ET
# 加载XML文件
tree = ET.parse('example.xml')
# 获取根元素
root = tree.getroot()
# 遍历根元素下的所有子元素
for child in root:
# 输出子元素的标签和文本内容
print(child.tag, child.text)
In the example above, we start by using the ET.parse() function to load the XML file, and then use the tree.getroot() method to retrieve the root element. Next, we use a loop to iterate through all the child elements under the root element, and use the child.tag and child.text attributes to respectively get the child element’s tag and text content.
Please note that in the above code, example.xml is the path of the XML file you want to read, you need to replace it with your own file path.