Need help understanding etree xml for python working with tag structure
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...
I have the following xml structure in a file:
<sss version="1.2">
<date>2011-09-23</date>
<time>12:32:29</time>
<origin>OPST</origin>
<user></user>
<survey>
<name>Test</name>
<version>2011-09-02 15:50:10</version>
<record ident="A">
<variable ident="10" type="quantity">
<name>v_682</name>
<label>Another question</label>
<position start="23" finish="24"/>
<values>
<range from="0" to="32"/>
</values>
</variable>
<variable ident="11" type="quantity">
<name>v_683</name>
<label>another totally another Question</label>
<positio开发者_Go百科n start="25" finish="26"/>
<values>
<range from="0" to="33"/>
</values>
</variable>
<variable ident="12" type="quantity">
<name>v_684</name>
<label>And once more Question</label>
<position start="27" finish="29"/>
<values>
<range from="0" to="122"/>
</values>
</variable>
<variable ident="20" type="single">
<name>v_685</name>
<label>Question with alternatives</label>
<position start="73" finish="73"/>
<values>
<range from="1" to="6"/>
<value code="1">Alternative 1</value>
<value code="2">Alternative 2</value>
<value code="3">Alternative 3</value>
<value code="6">Alternative 4</value>
</values>
</variable>
</record>
</survey>
</sss>
to read elements i developed a pretty bad loop, that does not match the capabilities of the etree library i guess...
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
How can i make use of the tag structure: for instance to read the "value" tag for appending the text into a list?
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
If the file is small and you only need <value/>
elements:
#!/usr/bin/env python
import xml.etree.cElementTree as etree
tree = etree.parse('scheme.xml')
for value in tree.getiterator(tag='value'):
print value.get('code'), value.text
If the file is large:
def getelements(filename, tag):
context = iter(etree.iterparse(filename, events=('start', 'end')))
_, root = next(context) # get root element
for event, elem in context:
if event == 'end' and elem.tag == tag:
yield elem
root.clear() # free memory
for elem in getelements('scheme.xml', 'value'):
print elem.get('code'), elem.text
Output
1 Alternative 1
2 Alternative 2
3 Alternative 3
6 Alternative 4
To find out more, read Searching for Subelements and The ElementTree XML API.
精彩评论