Reputation: 4239
I have written the following python code to parse a XML file with lxml. I am confused why it is returning a memory address but not the actual output height
in this case.
import pdb
from pprint import pprint
from lxml import etree
def main():
parser = etree.XMLParser(strip_cdata = False)
tree = etree.parse("xml.xml", parser)
string = etree.tostring(tree.getroot())
content = etree.fromstring(string)
bodies = content.findall('Body')
all_data = []
for body in bodies:
row = {}
height = body.findall('height')
row['height'] = height
all_data.append(row)
print all_data
pdb.set_trace()
The output that I got is:
[{'height': [<Element height at 0x11ac80830>]}]
whereas I expect a height of 178
.
The data within the xml file is:
<Bodies>
<Body>
<name><![CDATA[abc]]></name>
<body_name><![CDATA[asdjakhdas da sdasda sd]]></body_name>
<final_height><![CDATA[199]]></final_height>
<categories><![CDATA[a / b / c]]></categories>
<hand><![CDATA[asdkj]]></hand>
<height>178</height>
</Body>
<Bodies>
Upvotes: 0
Views: 892
Reputation: 295272
If you don't want to put the height element into your variable, but instead the text field it contains:
height = body.find('height')
row['height'] = float(height.text) if height else None
Note the use of find
as opposed to findall
-- findall
returns a list, whereas it sounds like you're expecting only a single value (and have no need to recurse).
Upvotes: 2