Xml - 使用 Python 按标签查找元素 [英] Xml - Find Element By tag using Python

查看:47
本文介绍了Xml - 使用 Python 按标签查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一堆 xml 文件中提取一些数据.现在,问题是所有文件的结构并不完全相同,因此,仅迭代子项并提取值是很困难的.

I am trying extract some data from a bunch of xml files. Now, the issue is the structure of all the files is not exactly the same and thus, just iterating over the children and extracting the values is difficult.

对于这样的 xml 文档,python 是否有 getElementByTag() 方法?我已经看到这样的方法适用于 C#、C++ 用户,但找不到任何适用于 Python 的方法.

Is there a getElementByTag() method for python for such xml documents? I have seen that such a method is available for C#, C++ users but couldn't find anything for Python.

任何帮助将不胜感激!

推荐答案

是的,在包 xml.etree 可以找到与 XML 相关的内置函数.(也可用于python2)

Yes, in the package xml.etree you can find the built-in function related to XML. (also available for python2)

您要特别寻找的是findall.

例如:

import xml.etree.ElementTree as ET
tree = ET.fromstring(some_xml_data)
all_name_elements = tree.findall('.//name')

与:

In [1]: some_xml_data = "<help><person><name>dean</name></person></help>"

我得到以下信息:

In [10]: tree.findall(".//name")
Out[10]: [<Element 'name' at 0x7ff921edd390>]

这篇关于Xml - 使用 Python 按标签查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆