【问题标题】:Retrieving data from xml.从 xml 中检索数据。
【发布时间】:2016-07-17 10:56:49
【问题描述】:

我有一个 xml 文件,我必须通过它来检索 xml 文档。 下面是我的xml文档。

-<orcid-message>
   -<orcid-profile type="user">
      -<orcid-activities>
         -<orcid-works>
            -<orcid-work put-code="23938140" visibility="public">
               -<work-contributors>
                  -<contributor>
                       -<credit-name visibility="public">Tania Maes</credit-name>
                  -<contributor>
                       -<credit-name visibility="public">Francisco Avila Cobos</credit-name>
                  -<contributor>
                       -<credit-name visibility="public">Franco Liala Manus</credit-name>

我想检索贡献者姓名: 到目前为止我已经尝试过:

contributors_name = (doc['orcid-message']['orcid-profile']
                        ['orcid-activities']['orcid-works']
                        ['orcid-work']['work-contributors']
                        ['contributor']['credit-name']  )

print(contributors_name)

请告诉我哪里出错了。谢谢。

【问题讨论】:

  • 什么是doc 变量?你是如何填充它的?
  • doc = xmltodict.parse(fd.read()) 而fd是xml文档
  • 您当前的代码有什么问题?什么都没有打印出来或抛出任何异常?
  • contributors_name = (doc['orcid-message']['orcid-profile']['orcid-activities']['orcid-works']['orcid-work']['work -contributors']['contributor']['credit-name'] ) TypeError: list indices must be integers, not str : 我明白了。

标签: python xml python-3.x xmltodict


【解决方案1】:

TypeError: list indices must be integers, not str:我收到此错误”

错误消息表明问题是由于 XML 包含多个 contributor 元素,因此您的代码到 ['contributor'] 部分将返回一个列表,而该列表又不能通过键直接访问(即 @ 987654324@) 就像字典一样。您需要在列表中选择一个您想从中获取credit-name 的项目,例如从第一项:

contributors = doc['orcid-message']['orcid-profile'] \
    ['orcid-activities']['orcid-works'] \
    ['orcid-work']['work-contributors'] \
    ['contributor']
contributor_name = contributors[0]['credit-name']

或者您可以使用列表推导从所有贡献者那里获取credit-name

contributors_name = [contrib['credit-name']['#text'] for contrib in contributors]
print(contributors_name)

输出:

[u'Tania Maes', u'Francisco Avila Cobos', u'Franco Liala Manus']

【讨论】:

  • 我仍然遇到同样的错误。当我分配时:contributors = doc['orcid-message']['orcid-profile'] ['orcid-activities']['orcid-works'] ['orcid-work']['work-contributors'] [ '贡献者']。它给出了同样的错误。
  • 除了contributor之外,实际的 XML 是否包含多个同名元素,在您的评论代码中提到?
  • 是的,它确实包含。也许我应该使用 E-tree lib。你用哪个库来获取输出?
  • xmltodict 因为问题是使用这个库。但在我的测试中,只有 contributorcredit-name 是多个(基于 XML sn-p 发布的问题),所以它工作正常。
猜你喜欢
  • 2023-04-01
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多