Parse XML using Python and xml.etree -
i have xml file , i'd read data out of using python's xml.etree.
let's xml file :
<a> <b> <c> <d>this text want retrieve</d> </c> </b> </a> what did :
document = elementtree.parse('file.xml') dtofind = document.find('d') print(dtofind.text) but gave me following error :
print(dtofind.text) attributeerror: 'nonetype' object has no attribute 'text' what did wrong? , how can fix it?
thanks!
you can use xpath more sophesticated parsing combined find finding node recursively
in case:
dtofind = document.find('.//d') the documentation points more structured parsing using xpath - encourage that.
demo
>>> xml.etree import elementtree et >>> content = """<a> ... <b> ... <c> ... <d>this text want retrieve</d> ... </c> ... </b> ... </a> ... """ >>> >>> xx = et.fromstring(file) #you doing .parse() >>> xx.find('d') #returns none, finds first level children >>> xx.find('.//d') <element 'd' @ 0xf1b550> >>> d = xx.find('.//d') >>> d.text 'this text want retrieve'
Comments
Post a Comment