Python: 使用 xmltodict 获取值

Python: Get value with xmltodict

我有一个 XML 文件,如下所示:

<?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。这可能很简单,但我似乎无法弄明白。

这是我的代码:

#!/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 每个单独的字段属性或元素都可以作为键值访问。 我如何访问值 "Jake Roberts" 就像访问 docVersion 的值一样?

您得到的是一个字段列表,其中每个字段都由 dict() 表示。探索这个字典(例如在 Python interactive shell 中)以缩小如何获得你想要的值的范围。

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

为了获取元素值,请将 ["#text"] 添加到上面代码段的行尾。