Note that there are some explanatory texts on larger screens.

plurals
  1. POPython and libxml2: how to iterate in xml nodes with XPATH
    text
    copied!<p>I have a problem with retrieving information from a XML tree.</p> <p>My XML has this shape:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;records xmlns="http://www.mysyte.com/foo"&gt; &lt;record&gt; &lt;id&gt;first&lt;/id&gt; &lt;name&gt;john&lt;/name&gt; &lt;papers&gt; &lt;paper&gt;john_1&lt;/paper&gt; &lt;paper&gt;john_2&lt;/paper&gt; &lt;/papers&gt; &lt;/record&gt; &lt;record&gt; &lt;id&gt;second&lt;/id&gt; &lt;name&gt;mike&lt;/name&gt; &lt;papers&gt; &lt;paper&gt;mike_a&lt;/paper&gt; &lt;paper&gt;mike_b&lt;/paper&gt; &lt;/papers&gt; &lt;/record&gt; &lt;record&gt; &lt;id&gt;third&lt;/id&gt; &lt;name&gt;albert&lt;/name&gt; &lt;papers&gt; &lt;paper&gt;paper of al&lt;/paper&gt; &lt;paper&gt;other paper&lt;/paper&gt; &lt;/papers&gt; &lt;/record&gt; &lt;/records&gt; </code></pre> <p>What I want to do is to extract tuples of data like the follow:</p> <pre><code>[{'code': 'first', 'name': 'john'}, {'code': 'second', 'name': 'mike'}, {'code': 'third', 'name': 'albert'}] </code></pre> <p>Now I wrote this python code:</p> <pre><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}) </code></pre> <p>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.</p> <p>I also tried with these XPATHs for the id and the name:</p> <pre><code>/id /name /record/id /record/name /pre:id /pre:name </code></pre> <p>and so on, but with any result (BTW if I use the prefix in the sub queries I have an error).</p> <p>Any idea?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload