Xml - 使用 Python 按标签查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38309395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Xml - Find Element By tag using Python
提问by Rishabh Ranawat
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 文件中提取一些数据。现在,问题是所有文件的结构并不完全相同,因此,仅迭代子项并提取值是很困难的。
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.
getElementByTag()
这样的xml文档有python的方法吗?我已经看到这样的方法适用于 C#、C++ 用户,但找不到任何适用于 Python 的方法。
Any help will be much appreciated!
任何帮助都感激不尽!
回答by Dean Fenster
Yes, in the package xml.etreeyou can find the built-in function related to XML. (also available for python2)
是的,在包xml.etree 中,您可以找到与 XML 相关的内置函数。(也可用于python2)
The one specifically you are looking for is findall
.
您正在寻找的具体内容是findall
.
For example:
例如:
import xml.etree.ElementTree as ET
tree = ET.fromstring(some_xml_data)
all_name_elements = tree.findall('*/name')
With:
和:
In [1]: some_xml_data = "<help><person><name>dean</name></person></help>"
I get the following:
我得到以下信息:
In [10]: tree.findall("*/name")
Out[10]: [<Element 'name' at 0x7ff921edd390>]