當前位置:成語大全網 - 新華字典 - 如何使用Python和xml.etree.ElementTree解析xml文件獲取其節點

如何使用Python和xml.etree.ElementTree解析xml文件獲取其節點

<?xml?version?=?"1.0"?encoding?=?"utf-8"?>

<root>

<body?name="lyc">

<age>110</age>

</body>

<body?name?=?"l"?age?=?"10">

</body>

</root>

######################

#coding=UTF8

from?xml.etree?import?ElementTree

#xmlText?=?open("xml.txt").read()

#root?=?ElementTree.fromstring(xmlText)

root?=?ElementTree.parse("xml.txt")

bodys?=?root.getiterator("body")

#getiterator方法獲取

print?"getiterator"

print?bodys

print?dir(bodys[0])

print?"attrib:",bodys[0].attrib

print?"tag:",bodys[0].tag

print?"text",bodys[0].text

#getchildren方法獲取

print?"getchildren"

children?=?bodys[0].getchildren()

print?children

print?"attrib:",children[0].attrib

print?"tag:",children[0].tag

print?"text:",children[0].text

#find

print?"find"

children?=?root.find("body")

print?children

print?"attrib:",children.attrib

print?"tag:",children.tag

print?"text:",children.text

#findall?

print?"findall"

children?=?root.findall("body")

print?children

print?"attrib:",children[0].attrib

print?"tag:",children[0].tag

print?"text:",children[0].text