我有一些问题需要解决python etree库来读取xml文件。 我在python中编程很新...所以xml对我来说有点怪......
我在文件中有以下xml结构:
<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>
<position 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>
读取元素我开发了一个非常糟糕的循环,这与我猜的etree库的功能不匹配...
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
如何使用标记结构:例如,读取“value”标记以将文本附加到列表中?
对我来说,这些etree教程非常难以喘息......也许有人可以告诉我如何使用基于标签的搜索...?这些循环太脆弱了...... Thanx很多
答案 0 :(得分:0)
如果文件很小而您只需要<value/>
个元素:
#!/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
如果文件很大:
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
1 Alternative 1
2 Alternative 2
3 Alternative 3
6 Alternative 4