Note that there are some explanatory texts on larger screens.

plurals
  1. PONeed help understanding etree xml for python working with tag structure
    text
    copied!<p>i'm having some problems to unterstand the python etree library to read a xml file. I pretty new with programming in python...so xml is kind of kinky for me...</p> <p>I have the following xml structure in a file:</p> <pre><code> &lt;sss version="1.2"&gt; &lt;date&gt;2011-09-23&lt;/date&gt; &lt;time&gt;12:32:29&lt;/time&gt; &lt;origin&gt;OPST&lt;/origin&gt; &lt;user&gt;&lt;/user&gt; &lt;survey&gt; &lt;name&gt;Test&lt;/name&gt; &lt;version&gt;2011-09-02 15:50:10&lt;/version&gt; &lt;record ident="A"&gt; &lt;variable ident="10" type="quantity"&gt; &lt;name&gt;v_682&lt;/name&gt; &lt;label&gt;Another question&lt;/label&gt; &lt;position start="23" finish="24"/&gt; &lt;values&gt; &lt;range from="0" to="32"/&gt; &lt;/values&gt; &lt;/variable&gt; &lt;variable ident="11" type="quantity"&gt; &lt;name&gt;v_683&lt;/name&gt; &lt;label&gt;another totally another Question&lt;/label&gt; &lt;position start="25" finish="26"/&gt; &lt;values&gt; &lt;range from="0" to="33"/&gt; &lt;/values&gt; &lt;/variable&gt; &lt;variable ident="12" type="quantity"&gt; &lt;name&gt;v_684&lt;/name&gt; &lt;label&gt;And once more Question&lt;/label&gt; &lt;position start="27" finish="29"/&gt; &lt;values&gt; &lt;range from="0" to="122"/&gt; &lt;/values&gt; &lt;/variable&gt; &lt;variable ident="20" type="single"&gt; &lt;name&gt;v_685&lt;/name&gt; &lt;label&gt;Question with alternatives&lt;/label&gt; &lt;position start="73" finish="73"/&gt; &lt;values&gt; &lt;range from="1" to="6"/&gt; &lt;value code="1"&gt;Alternative 1&lt;/value&gt; &lt;value code="2"&gt;Alternative 2&lt;/value&gt; &lt;value code="3"&gt;Alternative 3&lt;/value&gt; &lt;value code="6"&gt;Alternative 4&lt;/value&gt; &lt;/values&gt; &lt;/variable&gt; &lt;/record&gt; &lt;/survey&gt; &lt;/sss&gt; </code></pre> <p>to read elements i developed a pretty bad loop, that does not match the capabilities of the etree library i guess...</p> <pre><code>from xml.etree.cElementTree import parse et = parse(open('scheme.xml','rb')) root = et.getroot() for i in range(4): a= str(root[4][2][i][0].text) if a.startswith('v'): print root[4][2][i][1].text </code></pre> <p>How can i make use of the tag structure: for instance to read the "value" tag for appending the text into a list?</p> <p>For me these etree tutorials are pretty difficult to gasp...maybe someone can show me how to use a tag based search...? These loops are so fragile... Thanx a lot</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