Python:使用xmltodict获得价值 [英] Python: Get value with xmltodict

查看:226
本文介绍了Python:使用xmltodict获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的XML文件:

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>

使用xmltodict,我希望以字符串形式获取Employee.这可能很简单,但我似乎无法弄清楚.

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.

这是我的代码:

#!/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)

这样,我确实将列表中的所有字段都获取了,但是使用xmltodict可能可以将每个字段属性或元素作为键值进行访问. 如何像访问docVersion的值那样访问值"Jake Roberts"?

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?

推荐答案

您得到的是一个字段列表,其中每个字段都用dict()表示.探索此字典(例如,在Python交互式shell中)以缩小如何获得所需的值.

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')])

要获取元素值,请在上面的代码段的行末添加["#text"].

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

这篇关于Python:使用xmltodict获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆