Python daily practice - the first level of data storage: the method of reading XML node and attribute values

First round of interview questions:

Part 1 - Test Site:

  • Learn how to read XML node and attribute values.

Part 2 - Interview Questions:

1. Interview question 1: There is a test.xml file, which requires reading the values ​​of all child nodes of the products node in the file and the attribute values ​​of the child nodes.

test.xml file:

<!-- 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>

Part 3 - Analysis:

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

insert image description here

  • The XML document can be read through the parse function, which returns an object of type ElementTree, and the specific node in the XML can be iterated through the iterfind method of the object.

Guess you like

Origin blog.csdn.net/qq_44907926/article/details/123019133
Recommended