Using your example:

import xmltodict

with open('artikelen.xml') as fd:
    doc = xmltodict.parse(fd.read())

If you examine doc, you'll see it's an OrderedDict, ordered by tag:

>>> doc
OrderedDict([('artikelen',
              OrderedDict([('artikel',
                            [OrderedDict([('@nummer', '121'),
                                          ('code', 'ABC123'),
                                          ('naam', 'Highlight pen'),
                                          ('voorraad', '231'),
                                          ('prijs', '0.56')]),
                             OrderedDict([('@nummer', '123'),
                                          ('code', 'PQR678'),
                                          ('naam', 'Nietmachine'),
                                          ('voorraad', '587'),
                                          ('prijs', '9.99')])])]))])

The root node is called artikelen, and there is a subnode artikel which is a list of OrderedDict objects, so if you want the code for every article, you would do:

codes = []
for artikel in doc['artikelen']['artikel']:
    codes.append(artikel['code'])

# >>> codes
# ['ABC123', 'PQR678']

If you specifically want the code only when nummer is 121, you could do this:

code = None
for artikel in doc['artikelen']['artikel']:
    if artikel['@nummer'] == '121':
        code = artikel['code']
        break

That said, if you're parsing XML documents and want to search for a specific value like that, I would consider using XPath expressions, which are supported by ElementTree.

Answer from Paul on Stack Overflow
🌐
PyPI
pypi.org › project › xmltodict
xmltodict · PyPI
>>> xml = """ ... <root xmlns="http://defaultns.com/" ... xmlns:a="http://a.com/" ... xmlns:b="http://b.com/"> ... <x>1</x> ... <a:y>2</a:y> ... <b:z>3</b:z> ... </root> ... """ >>> xmltodict.parse(xml, process_namespaces=True) == { ... 'http://defaultns.com/:root': { ...
      » pip install xmltodict
    
Published   Feb 22, 2026
Version   1.0.4
🌐
Omz Software
omz-software.com › pythonista › docs › ios › xmltodict.html
xmltodict — Python 3.6.1 documentation
February 19, 2020 - Parse the given XML input and convert it into a dictionary. xml_input can either be a string or a file-like object. If xml_attribs is True, element attributes are put in the dictionary among regular child elements, using @ as a prefix to avoid collisions. If set to False, they are just ignored.
🌐
Readthedocs
xmltodict.readthedocs.io › en › stable › README
README - xmltodict
>>> import xmltodict >>> >>> mydict = { ... 'text': { ... '@color':'red', ... '@stroke':'2', ... '#text':'This is a test' ...
Top answer
1 of 4
36

Using your example:

import xmltodict

with open('artikelen.xml') as fd:
    doc = xmltodict.parse(fd.read())

If you examine doc, you'll see it's an OrderedDict, ordered by tag:

>>> doc
OrderedDict([('artikelen',
              OrderedDict([('artikel',
                            [OrderedDict([('@nummer', '121'),
                                          ('code', 'ABC123'),
                                          ('naam', 'Highlight pen'),
                                          ('voorraad', '231'),
                                          ('prijs', '0.56')]),
                             OrderedDict([('@nummer', '123'),
                                          ('code', 'PQR678'),
                                          ('naam', 'Nietmachine'),
                                          ('voorraad', '587'),
                                          ('prijs', '9.99')])])]))])

The root node is called artikelen, and there is a subnode artikel which is a list of OrderedDict objects, so if you want the code for every article, you would do:

codes = []
for artikel in doc['artikelen']['artikel']:
    codes.append(artikel['code'])

# >>> codes
# ['ABC123', 'PQR678']

If you specifically want the code only when nummer is 121, you could do this:

code = None
for artikel in doc['artikelen']['artikel']:
    if artikel['@nummer'] == '121':
        code = artikel['code']
        break

That said, if you're parsing XML documents and want to search for a specific value like that, I would consider using XPath expressions, which are supported by ElementTree.

2 of 4
-1

This is using xml.etree You can try this:

for artikelobj in root.findall('artikel'):
    print artikelobj.find('code')

if you want to extract a specific code based on the attribute 'nummer' of artikel, then you can try this:

for artikelobj in root.findall('artikel'):
    if artikel.get('nummer') == 121:
        print artikelobj.find('code')

this will print only the code you want.

🌐
AskPython
askpython.com › home › xmltodict module in python: a practical reference
xmltodict Module in Python: A Practical Reference - AskPython
December 9, 2020 - We can convert XML files to a Python dictionary using the xmltodict.parse() method in the xmltodict module.
🌐
GitHub
github.com › martinblech › xmltodict › blob › master › xmltodict.py
xmltodict/xmltodict.py at master · martinblech/xmltodict
>>> doc = xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a> ... \"\"\") >>> doc['a']['@prop'] 'x' >>> doc['a']['b'] ['1', '2'] · If `item_depth` is `0`, the function returns a dictionary for the root ·
Author   martinblech
🌐
GitHub
github.com › martinblech › xmltodict
GitHub - martinblech/xmltodict: Python module that makes working with XML feel like you are working with JSON · GitHub
February 16, 2014 - >>> print(json.dumps(xmltodict.parse(""" ... <mydocument has="an attribute"> ... <and> ... <many>elements</many> ... <many>more elements</many> ... </and> ... <plus a="complex"> ... element as well ... </plus> ... </mydocument> ...
Starred by 5.7K users
Forked by 468 users
Languages   Python
Find elsewhere
🌐
Snyk
snyk.io › advisor › xmltodict › functions › xmltodict.parse
How to use the xmltodict.parse function in xmltodict | Snyk
def __list_tasks(api_call, output_format='dict'): xml_string = openml._api_calls._perform_api_call(api_call, 'get') tasks_dict = xmltodict.parse(xml_string, force_list=('oml:task', 'oml:input')) # Minimalistic check if the XML is useful if 'oml:tasks' not in tasks_dict: raise ValueError('Error in return XML, does not contain "oml:runs": %s' % str(tasks_dict)) elif '@xmlns:oml' not in tasks_dict['oml:tasks']: raise ValueError('Error in return XML, does not contain ' '"oml:runs"/@xmlns:oml: %s' % str(tasks_dict)) elif tasks_dict['oml:tasks']['@xmlns:oml'] != 'http://openml.org/openml': raise ValueError('Error in return XML, value of ' '"oml:runs"/@xmlns:oml is not ' '"http://openml.org/openml": %s' % str(tasks_dict)) assert type(tasks_dict['oml:tasks']['oml:task']) == list, \
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-xml-to-json-dict
Python XML to JSON, XML to Dict | DigitalOcean
August 3, 2022 - Let’s see the output for this program: Here, we simply use the parse(...) function to convert XML data to JSON and then we use the json module to print JSON in a better format. Keeping XML data in the code itself is neither always possible nor it is realistic.
🌐
The Hitchhiker's Guide to Python
python-docs.readthedocs.io › en › latest › scenarios › xml.html
XML parsing - The Hitchhiker's Guide to Python - Read the Docs
import untangle obj = untangle.parse('path/to/file.xml') and then you can get the child elements name like this: obj.root.child['name'] untangle also supports loading XML from a string or an URL. xmltodict is another simple library that aims at making XML feel like working with JSON.
🌐
The Hitchhiker's Guide to Python
docs.python-guide.org › scenarios › xml
XML parsing — The Hitchhiker's Guide to Python
xmltodict also lets you roundtrip back to XML with the unparse function, has a streaming mode suitable for handling files that don’t fit in memory, and supports XML namespaces. xmlschema provides support for using XSD-Schemas in Python. Unlike other XML libraries, automatic type parsing is ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-convert-xml-to-dictionary
Python program to convert XML to Dictionary - GeeksforGeeks
July 23, 2025 - Use xmltodict.parse() to parse the content from the variable and convert it into Dictionary.
🌐
Tanium
tanium.github.io › pytan › _modules › xmltodict.html
xmltodict — PyTan v2.1.6 2.1.6 documentation
[docs]def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', **kwargs): """Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like object. If `xml_attribs` is `True`, element attributes are ...
🌐
Calazan
calazan.com › easily-convert-xml-data-to-a-python-dict-with-xmltodict
Easily convert XML data to a Python dict with xmltodict | Calazan.com
September 1, 2019 - The xmltodict package allows us to easily convert that XML data to a Python dictionary which is much nicer to work with. It has pretty much handled all the scenarios we've seen so far. This includes XML feeds that use attributes instead of elements and also those that use CDATA sections.
🌐
Wimwauters
blog.wimwauters.com › networkprogrammability › 2020-01-09-parse_xml_python
Parse XML file with Python - Technology Blog Wim
January 9, 2020 - import xmltodict with open('sample.xml') as f: xml_content = f.read() xml_dict = xmltodict.parse(xml_content) customers = xml_dict['Root']['Customers'] orders = xml_dict['Root']['Orders'] #print(orders) customer_list = [] for customer in customers['Customer']: customer_list.append(customer['@CustomerID']) for customer in customer_list: print(f"Orders for: {customer}") for order in orders['Order']: if(customer == order['CustomerID']): print(f" ==>Employee {order['EmployeeID']} placed an order on {order['OrderDate']}")
🌐
MicroPyramid
micropyramid.com › blog › how-to-convert-xml-content-into-json-using-xmltodict
How to Convert XML Content into Json Using XMLtodict | MicroPyramid
>>> import xmltodict >>> import json >>> json.loads(json.dumps(xmltodict.parse(''' <root> <persons city="hyderabad"> <person name="abc"> <name age="50" mobile="789" /> </person> </persons> <persons city="vizag"> <username></username> <person name="xyz"> <name age="70" mobile="123" /> </person> </persons> </root> '''))) {u'root': {u'persons': [{u'@city': u'hyderabad', u'person': {u'@name': u'abc', u'name': {u'@mobile': u'789', u'@age': u'50'}}}, {u'@city': u'vizag', u'person': {u'@name': u'xyz', u'name': {u'@mobile': u'123', u'@age': u'70'}}}]}} >>> xmltodict.unparse({u'root': {u'persons': [{u'
🌐
GitHub
gist.github.com › e0a3a936e68a9668e226
A quick tutorial on using xmltodict to parse civic data. · GitHub
A quick tutorial on using xmltodict to parse civic data. - xmldict-tutorial.ipynb
🌐
CloudDefense.ai
clouddefense.ai › code › python › example › xmltodict
Top 10 Examples of <!-- -->xmltodict<!-- --> code in Python | CloudDefense.AI
def __list_tasks(api_call, output_format='dict'): xml_string = openml._api_calls._perform_api_call(api_call, 'get') tasks_dict = xmltodict.parse(xml_string, force_list=('oml:task', 'oml:input')) # Minimalistic check if the XML is useful if 'oml:tasks' not in tasks_dict: raise ValueError('Error in return XML, does not contain "oml:runs": %s' % str(tasks_dict)) elif '@xmlns:oml' not in tasks_dict['oml:tasks']: raise ValueError('Error in return XML, does not contain ' '"oml:runs"/@xmlns:oml: %s' % str(tasks_dict)) elif tasks_dict['oml:tasks']['@xmlns:oml'] != 'http://openml.org/openml': raise ValueError('Error in return XML, value of ' '"oml:runs"/@xmlns:oml is not ' '"http://openml.org/openml": %s' % str(tasks_dict)) assert type(tasks_dict['oml:tasks']['oml:task']) == list, \
🌐
Pythonrepo
pythonrepo.com › repo › martinblech-xmltodict-python-working-with-html-and-xml
Python module that makes working with XML feel like you are working with JSON | PythonRepo
January 12, 2022 - The parse_lxml() method should take the same options as the parse() method. ... >>> xml = etree.XML("<a><b>data</b></a>") >>> xmltodict.parse_lxml(xml, new_style=True).prettyprint() {'a': {'b': u'data'}}