Home  >  Article  >  Backend Development  >  How does xmltodict operate on xml in Python?

How does xmltodict operate on xml in Python?

WBOY
WBOYforward
2023-05-04 18:04:141203browse

Python xmltodict's operation on xml

xmltodict is another simple library that is dedicated to turning XML into JSON.

The following is a simple example XML file:

<?xml version="1.0"?>
<mydocument has="an attribute">
    <and>
        <many>elements</many>
        <many>more elements</many>
    </and>
    <plus a="complex">
        element as well
    </plus>
</mydocument>

This is a third-party package. Use pip to install it before processing.

pip install xmltodict

You can access the elements, attributes and values ​​inside as follows:

import xmltodict
 
with open("test.xml") as fd:          # 将XML文件装载到dict里面
    doc = xmltodict.parse(fd.read())
    print(doc["mydocument"]["@has"])  # an attribute
    print(doc["mydocument"]["and"])   # OrderedDict([(u&#39;many&#39;, [u&#39;elements&#39;, u&#39;more elements&#39;])])
    print(doc["mydocument"]["and"]["many"])   # [u&#39;elements&#39;, u&#39;more elements&#39;]
    print(doc["mydocument"]["plus"]["@a"])    # complex
    print(doc["mydocument"]["plus"]["#text"]) # element as well
xmltodict 也有unparse函数让您可以转回XML。

This function has a Streaming mode is suitable for processing files that cannot be placed in memory. It also supports namespace

Python XML parsing, xmltodict module

Install xmltodict: pip3 install xmltodict

demo. py (xml string parsed into dictionary-like):

# coding:utf-8
import xmltodict   # 导入
 
# XML格式字符串
xml_str = """
        <xml>
            <Name>张三</Name>
            <age>18</age>
        </xml>
        """
 
 
xml_dict = xmltodict.parse(xml_str)   # 解析xml字符串
 
print(type(xml_dict))  # <class &#39;collections.OrderedDict&#39;>  类字典型,可以按照字典方法操作
 
print xml_dict
 
# 遍历
for key, val in xml_dict[&#39;xml&#39;].items():
    print key, "---", val

demo.py (dictionary converted into xml string):

# coding:utf-8
import xmltodict   # 导入
 
# 字典
xml_dict = {
                "xml": {
                    "name" : u"张三",
                    "age" : 18
                }
            }
 
# 字典转换成XML字符串
# xml_str = xmltodict.unparse(xml_dict)
xml_str = xmltodict.unparse(xml_dict, pretty=True)  # pretty表示友好输出(有换行)
 
print(xml_str)

The above is the detailed content of How does xmltodict operate on xml in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete