python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python读取XML

Python练习之读取XML节点和属性值的方法

作者:​ 孤寒者   ​

这篇文章主要介绍了Python练习之读取XML节点和属性值的方法,通过parse函数可以读取XML文档,该函数返回ElementTree类型的对象,通过该对象的iterfind方法可以对XML中特定节点进行迭代

面试题

有一个test.xml文件,要求读取该文件中products节点的所有子节点的值以及子节点的属性值。

test.xml文件:

<!-- products.xml -->
<root>
    <products>
        <product uuid='1234'>
            <id>10000</id>
            <name>苹果</name>
            <price>99999</price>
        </product>
        <product uuid='1235'>
            <id>10001</id>
            <name>小米</name>
            <price>999</price>
        </product>
        <product uuid='1236'>
            <id>10002</id>
            <name>华为</name>
            <price>9999</price>
        </product>
    </products>
</root>

解析

# coding=utf-8
from xml.etree.ElementTree import parse
doc = parse('./products.xml')
print(type(doc))

for item in doc.iterfind('products/product'):
    id = item.findtext('id')
    name = item.findtext('name')
    price = item.findtext('price')
    uuid = item.get('uuid')
    print('uuid={}, id={}, name={}, price={}'.format(uuid, id, name, price), end='\n----------\n')

到此这篇关于Python练习之读取XML节点和属性值的方法的文章就介绍到这了,更多相关Python读取XML内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文