Python3处理XML格式的数据

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>

读取与搜索XML文件

from xml.etree.ElementTree import parse
doc = parse('products.xml')
# 通过XPath搜索子节点集合,然后对子节点集合进行遍历
for item in doc.iterfind('products/product'):
    id = item.findtext('id') # 读取product节点的id子节点的值
    name = item.findtext('name') # 读取product节点的name子节点的值
    price = item.findtext('price')
    print('uuid =', item.get('uuid')) # 读取product节点的uuid属性的值
    print('id =', id)
    print('name =', name)
    print('price =', price)
    print('----------------------')

输出结果:

uuid = 1234
id = 10000
name = iPhone9
price = 9999
----------------------
uuid = 4321
id = 20000
name = 特斯拉
price = 800000
----------------------
uuid = 5678
id = 30000
name = Mac Pro
price = 40000
----------------------

字典转换为XML字符串

  • 将字典转换为XML文件需要使用 dicttoxml模块 中的 dicttoxml 函数,使用 pip 命令安装该模块:pip install dicttoxml

  • 用例:

import dicttoxml
from xml.dom.minidom import parseString
import os

# 定义一个列表
d = [20, 'names',
     {'name': 'Bill', 'age': 30, 'salary': 2000},
     {'name': 'Jack', 'age': 34, 'salary': 3000},
     {'name': 'John', 'age': 25, 'salary': 2500}]
# 转换为XML格式(bytes形式)
bxml = dicttoxml.dicttoxml(d, custom_root='persons')
xml = bxml.decode('utf-8')
print(xml)
# 解析XML字符串
dom = parseString(xml)
# 生成带缩进格式的XML字符串
prettyxml = dom.toprettyxml(indent='    ')
# 写入文件
f = open('persons.xml', 'w')
f.write(prettyxml)
f.close()

转换后的XML文件内容:

<?xml version="1.0" ?>
<persons>
    <item type="int">20</item>
    <item type="str">names</item>
    <item type="dict">
        <name type="str">Bill</name>
        <age type="int">30</age>
        <salary type="int">2000</salary>
    </item>
    <item type="dict">
        <name type="str">Jack</name>
        <age type="int">34</age>
        <salary type="int">3000</salary>
    </item>
    <item type="dict">
        <name type="str">John</name>
        <age type="int">25</age>
        <salary type="int">2500</salary>
    </item>
</persons>

转载于:https://my.oschina.net/zerobit/blog/3079297

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值