Python: Get value with xmltodict

家住魔仙堡 提交于 2019-12-14 03:16:48

问题


I have an XML-file that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<session id="2934" name="Valves" docVersion="5.0.1">
    <docInfo>
        <field name="Employee" isMandotory="True">Jake Roberts</field>
        <field name="Section" isOpen="True" isMandotory="False">5</field>
        <field name="Location" isOpen="True" isMandotory="False">Munchen</field>
    </docInfo>
</session>

Using xmltodict I want to get the Employee in a string. It is probably quite simple but I can't seem to figure it out.

Here's my code:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import sys
import xmltodict


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


print "ID          : %s" % doc['session']['@id']
print "Name        : %s" % doc['session']['@name']
print "Doc Version : %s" % doc['session']['@docVersion']


print "Employee    : %s" % doc['session']['docInfo']['field']


sys.exit(0)

With this, I do get all fields in a list, but probably with xmltodict every individual field attribute or element is accessible as a key-value. How can I access the value "Jake Roberts" like I access the value of docVersion for example?


回答1:


What you are getting is a list of fields where every field is represented by a dict(). Explore this dict (e.g. in Python interactive shell) to narrow down how to get to the value you want.

>>> doc["session"]["docInfo"]["field"][0]
OrderedDict([(u'@name', u'Employee'), (u'@isMandotory', u'True'), ('#text', u'Jake Roberts')])

In order to get to the element value add ["#text"] to the end of the line in the snippet above.



来源:https://stackoverflow.com/questions/36253405/python-get-value-with-xmltodict

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!