xml解析(ElementTree)

try:

    import  xml.etree.cElementTree  as ET

except Import  Error:

     import   xml.etree.ElementTree  as  ET

请注意 自python3.3 以后,就不采用上面的导入方式,因为,ElementTree

模块会自动优先加载c加速器,如果不存在C实现,则会用Python实现,因此:

使用Python3.3以上的朋友,只需导入 import  xml.etree.ElementTree即可。


XML是一种结构化、层级化的数据结构,最适合体现XML的数据结构就是树,

tree = ET.parse("1.xml")  #解析文件
root = tree.getroot()      #得到根节点
 
 
allbook = tree.findall(root[0].tag)  #查找树结构中所有子节点的标签地址的列表
print(allbook)     #[<Element 'book' at 0x00000000026F2E08>, <
                    # Element 'book' at 0x0000000002876E08>, <Element 'book' at 0x000000000289DAE8>]

for b in allbook:    #遍历列表,查找每一个子节点标签中的文本
    bname = b.find(root[0][0].tag).text
    price = b.find(root[0][1].tag).text
    author = b.find(root[0][2].tag).text
    break
    print("书名:%s 作者:%s  价格:%s"%(bname,price,author))


猜你喜欢

转载自blog.csdn.net/shilaike2/article/details/79446088
今日推荐