python的lxml和iterparse方法
假设我有这个示例 XML。
<result>
<field k='field1'>
<value h='1'><text>text_value1</text></value>
</field>
<field k='field2'>
<value><text>text_value2</text></value>
</field>
<field k='field3'>
<value><text>some_text</text></value>
</field>
</result>
使用python的lxml,如何获取每个结果集的每个字段的值?所以基本上,我想迭代所有结果集,然后迭代该结果集中的每个字段并打印文本数据。
这就是我到目前为止所拥有的:
context = etree.iterparse(contentBuffer, tag='result')
for action, elem in context:
print elem.tag, elem.data
任何帮助将不胜感激。
编辑 这是我想出的代码。必须调用 getparent() 两次来读取相应文本值的属性,这似乎有点笨拙。有更好的方法吗?
for action, elem in context:
list = elem.xpath('//text')
print "result set:"
for item in list:
field = item.getparent().getparent().attrib['k']
value = item.text
print "\t%s = %s"%(field, value)
Say i have this sample XML.
<result>
<field k='field1'>
<value h='1'><text>text_value1</text></value>
</field>
<field k='field2'>
<value><text>text_value2</text></value>
</field>
<field k='field3'>
<value><text>some_text</text></value>
</field>
</result>
Using python's lxml, how can i get the value of each field for every result set? So basically, i want to iterate over ever result set, then iterate over every field in that result set and print the text data.
This is what i have so far:
context = etree.iterparse(contentBuffer, tag='result')
for action, elem in context:
print elem.tag, elem.data
Any help would be greatly appreciated.
EDIT
Here is the code that i came up with. It seems a bit clunky having to call getparent() twice to read the attribute of corresponding text value. Is there a better way to do this?
for action, elem in context:
list = elem.xpath('//text')
print "result set:"
for item in list:
field = item.getparent().getparent().attrib['k']
value = item.text
print "\t%s = %s"%(field, value)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
哪个产量
How about:
which yields
我建议使用 XPath 查询。
r = tree.xpath('//text')
中的内容应该足以满足您的需求。I would suggest to use a XPath query. Something along
r = tree.xpath('//text')
should be sufficient for your needs.