xmltodict 模块

pip install xmltodict
xmltodict.parse() 方法可以将xml数据转为python中的dict字典数据
xmltodict.unparse() 将字典转换为xml数据
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>
# 将xml读出
    with open('file.xml') as fd:
        doc = xmltodict.parse(fd.read())
        print(doc['mydocument']['@has'])  # == u'an attribute'
        print(doc['mydocument']['and']['many'])  # == [u'elements', u'more elements']
        print(doc['mydocument']['plus']['@a'])  # == u'complex'
        print(doc['mydocument']['plus']['#text'])  # == u'element as well'

    # 将字典转换成xml
    with open('out.xml', 'w') as f:
        mydict = {
            'text': {
                '@color': 'red',
                ',
                '#text': 'This is a test'
            }
        }
        f.write(xmltodict.unparse(mydict))
        """ 生成的xml文件结果如下
        <?xml version="1.0" encoding="utf-8"?>
        <text stroke=" color="red">This is a test</text>
        """
上一篇:Android工具与其它


下一篇:[Python] Frequently used method or solutions for issues