Python每日一练——数据存储第一关:读取XML节点和属性值的方法

面试题第一关:

第一部分——考点:

  • 掌握读取XML节点和属性值的方法。

第二部分——面试题:

1.面试题一:有一个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
# _author__ = 孤寒者

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')

在这里插入图片描述

  • 通过parse函数可以读取XML文档,该函数返回ElementTree类型的对象,通过该对象的iterfind方法可以对XML中特定节点进行迭代。

猜你喜欢

转载自blog.csdn.net/qq_44907926/article/details/123019133