0

I'm trying to loop over an xml file with elementtree. The file looks a bit like this:

<items>
  <item>
    <name>Blah</name>
    <price>1234</price>
  </item>
  <item>
    <name>Something</name>
    <price>2345</price>
  </item>
</items>

After reading this with elementtree, I can do this:

for element in doc.findall('/items/item/name):
  print element.text

But with one loop, I'd like to get the price too... Something like this...

for element in doc.findall('/items/item'):
  print element.name.text
  print element.price.text

...but I can't. Not sure what's next - do I need to do another "find" per "element"?

Many thanks for any help!

4

2 回答 2

4

请阅读文档(http://docs.python.org/library/xml.etree.elementtree.html)。这是一个工作示例:

for elem in doc.findall('item'):
   for i in  elem.getchildren():
      print i.text

输出:

第1234章 2345

在我的代码中,我遍历 xml 中的所有项目并检索分配给其子节点的文本。

于 2011-02-01T22:40:59.267 回答
2

您可以使用以下内容对返回值进行精细控制。

for element in doc.findall('item'): # Get the items out.
    # Iterate thought the list of items(They are in element objects)

    print 'Item' # Yey print stuff out!
    print 'Name: ', element.find('name').text
    print 'Price:', element.find('price').text

输出以下内容:

Item
Name: Blah
Price: 1234
Item
Name: Something
Price: 2345

代码首先获取所有 item 元素。然后它执行查找以获取价格和名称并打印结果。此代码可确保您始终首先打印名称,然后打印价格。

于 2011-02-01T23:14:21.710 回答