使用Python ElementTree解析XML

编程入门 行业动态 更新时间:2024-10-09 05:14:59
本文介绍了使用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

本文发布于:2023-11-28 06:08:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641235.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   ElementTree   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!