python处理XML格式的数据

1. 读取XML文件

xml文件内容

<?xml version="1.0" ?>
    <products>
        <product uuid='1234'>
            <id>10000</id>
            <name>iphone</name>
            <price>1232</price>
        </product>
        <product uuid='1234'>
            <id>10001</id>
            <name>iphone5</name>
            <price>1232</price>
        </product>
        <product uuid='1234'>
            <id>10002</id>
            <name>iphone6</name>
            <price>1232</price>
        </product>
        <product uuid='1234'>
            <id>10003</id>
            <name>iphone10</name>
            <price>1232</price>
        </product>
    </products>
</root>

读取xml代码示例

xml文件是 product.xml from xml.etree.ElementTree import parse doc = parse('files/product.xml') # 开始分析xml文件 for item in doc.iterfind('products/product'): # 通过xpath搜索子节点集合,然后对这个子节点集合进行迭代 id = item.findtext('id') # 读取product节点的id子节点的值 name = item.findtext('name') # 读取product节点的name子节点的值 price = item.findtext('price') # 读取product节点的price子节点的值 print('uuid', '=', item.get('uuid')) # 读取product节点的uuid属性的值 print('id', '=', id) print('name', '=', name) print('price', '=', price) print('-'*20)

2. 字典转化为xml字符串

将字典转化为xml文件需要用到dicttoxml模块中的dicttoxml函数,需要安装导入dicttoxml模块

  • 安装dicttoxml模块:pip install dicttoxml
    将一个字典类型变量转换为XML字符串,然后再使用parseString函数解析这个XML字符串, 并用带缩进格式的形式将XML字符串写入到XML文件中 import dicttoxml from xml.dom.minidom import parseString import os # 定义一个字典 d = [20, 'names', {'name': 'bill', 'age': 30, 'salary': 2000}, {'name': 'mike', 'age': 67, 'salary': 8000}, {'name': 'john', 'age': 56, 'salary': 9000}] # 将字典转换为XML格式(bytes格式) bxml = dicttoxml.dicttoxml(d, custom_root='persons') xml = bxml.decode('utf-8') # 将bytes形式的XML数据按utf-8编码格式解码成XML字符串 print(xml) # 打印XML字符串 dom = parseString(xml) # 解析XML字符串 prettyxml = dom.toprettyxml(indent=' ') # 生存带缩进格式的XML字符串 os.makedirs('files', exist_ok=True) # 创建files目录 f = open('files/persons.xml', 'w', encoding='utf-8') # 以只写和utf-8编码格式的方式打开persons.xml文件 f.write(prettyxml) # 将格式化的XML字符串写入到persons.xml文件中 f.close()

    persons.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">mike</name>
            <age type="int">67</age>
            <salary type="int">8000</salary>
        </item>
        <item type="dict">
            <name type="str">john</name>
            <age type="int">56</age>
            <salary type="int">9000</salary>
        </item>
    </persons>
    

    3. XML字符串转换为字典

    将XML字符串转换成字典是上面的逆过程,需要安装和导入xmltodict模块

  • 安装xmltodict模块:pip install xmltodict
    import xmltodict
    import pprint
    f = open('files/product.xml', 'rt', encoding='utf-8')
    xml = f.read()
    d = xmltodict.parse(xml)  # 分析XML字符串,并转换为字典
    print(d)