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',
                '@stroke': '2',
                '#text': 'This is a test'
            }
        }
        f.write(xmltodict.unparse(mydict))
        """ 生成的xml文件結果以下
        <?xml version="1.0" encoding="utf-8"?>
        <text stroke="2" color="red">This is a test</text>
        """
相關文章
相關標籤/搜索