ยป pip install xmltodict
Videos
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.
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.
The issue can be resolved trough this simple way:
use 'pip' - python package manager
$ sudo pip install xmltodict
This should install missing module and you shouldn't have problems with this module.
As an answer, instead of in comments -> the issue is that you've got more than one python interpreter installed and you're getting a different one than you expected when you launched it via subprocess.check_output. You should address that by changing your invocation like so:
output = subprocess.check_output([sys.executable, filename,data], shell=False)
Which will ensure, at the very least, that both scripts are run by the same interpreter.
The package doesn't install any scripts or entry points. It only installs an importable module xmltodict.py. The module seems to be runnable but not directly executable so try python -m xmltodict:
cat run.tcx | python -m xmltodict 2
Since you are using python3.x, try using
sudo apt install python3-xmltodict