本文介绍了使用Python ElementTree解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下格式的XML文档
I have an XML document in the following format
<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中的所有文本标记。
How can I extract the text from 'D' inside H tag and also all the text inside the F tags.
推荐答案来自 ElementTree文档:
我们可以通过读取文件来导入此数据:
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。查找有趣的元素:
and later in the same page, 20.5.1.4. Finding interesting elements:
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更多推荐
使用Python ElementTree解析XML
发布评论