在Python中使用XML查找和提取数据 [英] Finding and Extracting Data using XML in Python
问题描述
您可以从XML的顶部开始到注释节点,然后遍历注释节点的子节点.
You could work from the top of the XML down to the comments node and then loop through the child nodes of the comments node.
我确定这是我需要做的,但是我不确定如何去做.
I am sure this is what I need to do but I'm not sure how to go about doing this.
我有一个类似于以下内容的XML数据结构:
I have an XML data structure similar to:
<level>
<name>Matthias</name>
<age>23</age>
<gender>Male</gender>
</level>
...
我试图通过将数据提取到Python中以进行数据验证,处理和输出,向用户显示姓名,年龄和字符性别.
I am trying to present the name, age and character gender to the user by extracting the data in to Python for data validation, processing and output.
如何从Python中的这些XML数据中仅提取玩家姓名?
How do I extract only the players name from these XML data in Python?
推荐答案
假定XML可以具有多个要遍历并读取详细信息的< level>
元素,这是一个可能的方式:
Assuming that the XML can have multiple <level>
elements that you want to loop through and read the details, this is one possible way :
from xml.etree import ElementTree as ET
source = '''<root>
<level>
<name>Matthias</name>
<age>23</age>
<gender>Male</gender>
</level>
<level>
<name>Foo</name>
<age>24</age>
<gender>Male</gender>
</level>
<level>
<name>Bar</name>
<age>25</age>
<gender>Male</gender>
</level>
</root>'''
root = ET.fromstring(source)
levels = root.findall('.//level')
for level in levels:
name = level.find('name').text
age = level.find('age').text
print name, age
输出:
Matthias 23
Foo 24
Bar 25
这篇关于在Python中使用XML查找和提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!