print(root.tag)# 根节点标签 for child in root: print(child.tag,child.attrib) # 二级节点标签、属性、内容,结果得到 # country {'name': 'Liechtenstein'} # country {'name': 'Singapore'} # country {'name': 'Panama'}
2、使用findall等查询根节点下的元素
Element.iter()用来寻找所有符合要求的Tag,注意,这里查找的范围是所有孩子和孩子的孩子 and so
root = ET.Element('data') country = ET.SubElement(root,'country', {'name':'Liechtenstein'}) # root 增加 country 节点 rank = ET.SubElement(country,'rank') # country 增加 rank 节点 rank.text = '1' year = ET.SubElement(country,'year') # country 增加 year节点 year.text = '2008' ET.dump(root)
5、XPath支持
XPath表达式用来在XML中定位Element,下面给一个例子来说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
importxml.etree.ElementTree as ET root = ET.fromstring(countrydata)
# Top-level elements root.findall(".") # All'neighbor' grand-children of'country' children of the top-level # elements root.findall("./country/neighbor") # Nodes withname='Singapore' that have a 'year' child root.findall(".//year/..[@name='Singapore']") # 'year' nodes that are children of nodes withname='Singapore' root.findall(".//*[@name='Singapore']/year") # All'neighbor' nodes that are the second child of their parent root.findall(".//neighbor[2]")