Jan-18-2019, 07:13 PM
**Note**: I named my file 'stuff.xml' change this line to your filename
You may have to install lxml if you don't already have it:
if you have to use earlier version for some reason, change line 15 to:
You may have to install lxml if you don't already have it:
pip install lxmland finally, I use f-string which requires python 3.6 or newer
if you have to use earlier version for some reason, change line 15 to:
print('tag: {}, value: {}'.format(element.tag, text))You should use lxml:
from lxml import etree import os def parse_xml(filename): os.chdir(os.path.abspath(os.path.dirname(__file__))) with open(filename) as fp: xml_text = fp.read() tree = etree.fromstring(xml_text) for kid in tree.getchildren(): for element in kid.getchildren(): text = None if element.text: text = element.text.strip() print(f'tag: {element.tag}, value: {text}') if __name__ == "__main__": parse_xml("stuff.xml")output:
Output:tag: rank, value: 1
tag: year, value: 2008
tag: gdppc, value: 141100
tag: neighbor, value: None
tag: neighbor, value: None
tag: rank, value: 4
tag: year, value: 2011
tag: gdppc, value: 59900
tag: neighbor, value: None
tag: rank, value: 68
tag: year, value: 2011
tag: gdppc, value: 13600
tag: neighbor, value: None
tag: neighbor, value: None