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'many', [u'elements', u'more elements'])]) print(doc["mydocument"]["and"]["many"]) # [u'elements', u'more elements'] 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 'collections.OrderedDict'> 类字典型,可以按照字典方法操作 print xml_dict # 遍历 for key, val in xml_dict['xml'].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!

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
