Finding and Extracting Data using XML in Python

狂风中的少年 提交于 2021-01-28 04:03:53

问题


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.

I have an XML data structure similar to:

<level>
  <name>Matthias</name>
  <age>23</age>
  <gender>Male</gender>
</level>
...

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.

How do I extract only the players name from these XML data in Python?


回答1:


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

output :

Matthias 23
Foo 24
Bar 25


来源:https://stackoverflow.com/questions/34589995/finding-and-extracting-data-using-xml-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!