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

How does xmltodict operate on xml in Python?

WBOY
Release: 2023-05-04 18:04:14
forward
1293 people have browsed it

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>
Copy after login

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

pip install xmltodict
Copy after login

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。
Copy after login

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
Copy after login

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)
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template