Feng’ Blog

Python dict to xml(不包含声明信息)
代码:1. from xml.etree.ElementTree import Element 2. from x...
扫描右侧二维码阅读全文
11
2018/12

Python dict to xml(不包含声明信息)

python_im.png

代码:

1. from xml.etree.ElementTree import Element
2. from xml.etree.ElementTree import tostring
3. @classmethod
4. def dict_to_xml(cls, tag, dic):
5. ​    """将传递的dict转换为xml(不包含声明信息)
6. ​    :param tag: 转换节点名称
7. ​    :param dic: 需要转换的dict字典
8. ​    :return :Element Object 需要使用tostring方法获取字符串
9. ​    """
10. ​    elem = Element(tag)
11. ​    for key, val in dic.items():
12. ​        if isinstance(val, dict):
13. ​            elem.append(cls.dict_to_xml(key, val))
14. ​        else:
15. ​            child = Element(key)
16. ​            child.text = str(val)
17. ​            elem.append(child)
18. ​    return elem

调用:

1. str_xml = {
2. ​            'CCTransCode': 'CQRA06',
3. ​            'ProductID': 'ICC',
4. ​            'ChannelType': 'ERP',
5. ​            'CorpNo': '123123',
6. ​            'Cmp': {
7. ​                'DbAccNo': '123',
8. ​                'DbProv': '01',
9. ​                'DbCur': '01',
10. ​            }
11. }
12. str_xml = dict_to_xml('ap', str_xml)
13. print tostring(str_xml)
Last modification:January 9th, 2019 at 01:48 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment