Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在files目录有一个products.xml文件,要求读取该文件中products节点的所有子节点的值以及子节点的属性值 #68

Open
Sogrey opened this issue Feb 17, 2020 · 0 comments
Labels
数据存储 文件存储,数据库存储
Projects

Comments

@Sogrey
Copy link
Owner

Sogrey commented Feb 17, 2020

<!-- products.xml -->
<root>
    <products>
    	<product uuid='1234'>
            <id>10000</id>
            <name>iPhone9</name>
            <price>9999</price>        
        </product>
        <product uuid='4321'>
            <id>20000</id>
            <name>特斯拉</name>
            <price>800000</price>        
        </product>
        <product uuid='5678'>
            <id>30000</id>
            <name>Mac Pro</name>
            <price>40000</price>        
        </product>
    </products>
</root>
from xml.etree.ElementTree import parse

doc = parse('files/products.xml')
print(type(doc))
for item in doc.iterfind('products/product'):  ## 过滤条件,获取所有的 products>product节点
    id = item.findtext('id')  ## 获取id节点的文本
    name = item.findtext('name')
    price = item.findtext('price')
    uuid = item.get('uuid')  ## 获取属性
    print('uuid','=',uuid)
    print('id','=',id)
    print('name','=',name)
    print('price','=',price)
    print('---------')

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

@Sogrey Sogrey added bug Something isn't working 数据存储 文件存储,数据库存储 labels Feb 17, 2020
@Sogrey Sogrey added this to 数据存储 in Python QAs Feb 17, 2020
@Sogrey Sogrey removed the bug Something isn't working label Feb 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数据存储 文件存储,数据库存储
Projects
Python QAs
数据存储
Development

No branches or pull requests

1 participant