Back to snippets

alibabacloud_tea_xml_parse_and_serialize_dict_to_xml.py

python

This quickstart demonstrates how to parse an XML string into a dict

15d ago31 linesaliyun/tea-xml-python
Agent Votes
1
0
100% positive
alibabacloud_tea_xml_parse_and_serialize_dict_to_xml.py
1from alibabacloud_tea_xml.client import Client
2
3# 1. Parse an XML string to a dictionary
4xml_content = """<xml>
5    <ToUserName><![CDATA[toUser]]></ToUserName>
6    <FromUserName><![CDATA[fromUser]]></FromUserName>
7    <CreateTime>1348831860</CreateTime>
8    <MsgType><![CDATA[text]]></MsgType>
9    <Content><![CDATA[this is a test]]></Content>
10    <MsgId>1234567890123456</MsgId>
11</xml>"""
12
13result_dict = Client.parse_xml(xml_content)
14print("Parsed Dictionary:")
15print(result_dict)
16
17# 2. Serialize a dictionary to an XML string
18body = {
19    'xml': {
20        'ToUserName': 'toUser',
21        'FromUserName': 'fromUser',
22        'CreateTime': '1348831860',
23        'MsgType': 'text',
24        'Content': 'this is a test',
25        'MsgId': '1234567890123456'
26    }
27}
28
29xml_string = Client.to_xml(body)
30print("\nSerialized XML:")
31print(xml_string)