Element Tree: How to parse subElements of child nodes

陌路散爱 提交于 2019-12-05 12:07:15

Since the XML document has a namespace declaration (xmlns="urn:ebay:apis:eBLBaseComponents"), you have to use universal names when referring to elements in the document. For example, you need {urn:ebay:apis:eBLBaseComponents}OrderID instead of just OrderID.

This snippet prints all OrderIDs in the document:

from xml.etree import ElementTree as ET

NS = "urn:ebay:apis:eBLBaseComponents"

tree = ET.parse('response.xml')

for elem in tree.iter("*"):    # Use tree.getiterator("*") in Python 2.5 and 2.6
    if elem.tag == '{%s}OrderID' % NS:
        print elem.text

See http://effbot.org/zone/element-namespaces.htm for details about ElementTree and namespaces.

Try to avoid chaining your finds. If your first find does not find anything, it will return None.

for child in root:
    order = child.find('Order')
    if order is not None:
        ids = order.find('OrderID')
        print ids.text

You can find an OrderArray first and then just iterate its children by name:

tree = ET.parse('response.xml')
root = tree.getroot()
order_array = root.find("OrderArray")
for order in order_array.findall('Order'):
    order_id_element = order.find('OrderID')
    if order_id_element is not None:
        print order_id_element.text

A side note. Never ever use except: continue. It hides any exception you get and makes debugging really hard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!