I have a problem with retrieving information from a XML tree.
My XML has this shape:
<?xml version="1.0"?>
<records xmlns="http://www.mysyte.com/foo">
<record>
<id>first</id>
<name>john</name>
<papers>
<paper>john_1</paper>
<paper>john_2</paper>
</papers>
</record>
<record>
<id>second</id>
<name>mike</name>
<papers>
<paper>mike_a</paper>
<paper>mike_b</paper>
</papers>
</record>
<record>
<id>third</id>
<name>albert</name>
<papers>
<paper>paper of al</paper>
<paper>other paper</paper>
</papers>
</record>
</records>
What I want to do is to extract tuples of data like the follow:
[{'code': 'first', 'name': 'john'},
{'code': 'second', 'name': 'mike'},
{'code': 'third', 'name': 'albert'}]
Now I wrote this python code:
try:
doc = libxml2.parseDoc(xml)
except (libxml2.parserError, TypeError):
print "Problems loading XML"
ctxt = doc.xpathNewContext()
ctxt.xpathRegisterNs("pre", "http://www.mysyte.com/foo")
record_nodes = ctxt.xpathEval('/pre:records/pre:record')
for record_node in record_nodes:
id = record_node.xpathEval('id')[0].content
name = record_node.xpathEval('name')[0].content
ret_list.append({'code': id, 'name': name})
My problem is that I don't have any result and I have the impression that I'm doing something wrong with the XPATH when I iterate on the nodes.
I also tried with these XPATHs for the id and the name:
/id
/name
/record/id
/record/name
/pre:id
/pre:name
and so on, but with any result (BTW if I use the prefix in the sub queries I have an error).
Any idea?