Skip to main content
 首页 » 编程设计

python之使用 Python ElementTree 解析 XML

2025年05月04日10cyq1162

我有一个以下格式的 XML 文档

<root> 
<H D="14/11/2017"> 
<FC> 
    <F LV="0">The quick</F> 
    <F LV="1">brown</F> 
    <F LV="2">fox</F> 
</FC> 
</H> 
<H D="14/11/2017"> 
<FC> 
    <F LV="0">The lazy</F> 
    <F LV="1">fox</F> 
</FC> 
</H> 
</root> 

如何从 H 标签内的“D”中提取文本以及 F 标签内的所有文本。

请您参考如下方法:

来自 ElementTree docs :

We can import this data by reading from a file:

import xml.etree.ElementTree as ET 
 
tree = ET.parse('country_data.xml') 
root = tree.getroot() 

Or directly from a string:

root = ET.fromstring(country_data_as_string) 

以及稍后在同一页面中的 20.5.1.4。寻找有趣的元素:

for neighbor in root.iter('neighbor'): 
    print(neighbor.attrib) 

转化为:

import xml.etree.ElementTree as ET 
 
root = ET.fromstring(""" 
<root> 
<H D="14/11/2017"> 
<FC> 
    <F LV="0">The quick</F> 
    <F LV="1">brown</F> 
    <F LV="2">fox</F> 
</FC> 
</H> 
<H D="14/11/2017"> 
<FC> 
    <F LV="0">The lazy</F> 
    <F LV="1">fox</F> 
</FC> 
</H> 
</root>""") 
# root = tree.getroot() 
for h in root.iter("H"): 
    print (h.attrib["D"]) 
for f in root.iter("F"): 
    print (f.attrib, f.text) 

输出:

14/11/2017 
14/11/2017 
{'LV': '0'} The quick 
{'LV': '1'} brown 
{'LV': '2'} fox 
{'LV': '0'} The lazy 
{'LV': '1'} fox