【问题标题】:How to extract data from from top level Element Tree XML elements?如何从顶级元素树 XML 元素中提取数据?
【发布时间】:2017-09-07 18:58:59
【问题描述】:

我正在学习 Python 的 XML 元素树。我已经根据自己的需要成功地从 API 中获取了 XML 响应,并使用我在网上找到的本指南对其进行了解析。 https://pymotw.com/2/xml/etree/ElementTree/parse.html

我的示例 XML 看起来像这样,调用中没有子对象:

<Response>
<Title>Student</Title>
<Date>7/18/2017 10:04:45 AM</Date>
<Description>Removed from group</Description>
</Response>

根据文章,我通过下面的响应迭代来提取元素树中的标签和属性:

tree = et.fromstring(xml_response)

for node in tree.iter('Group'):
    print node.tag, node.attrib

这使得所有的 XML 元素都变成了空字典项(我认为),并且显示如下:

Title{}
Date{}
Description{}

现在我想在每个调用中获取数据,这是我的尝试:

for node in tree.iter('Title'):
    Title = node.attrib.get('Title')
    print Title

我得到的输出是上述代码中的“无”。我的问题是 XML 标签之间的数据发生了什么变化,如何访问数据?

提前谢谢你。

【问题讨论】:

  • 你的代码是什么样的?源数据是什么样的?
  • @larsks 刚刚进行了编辑,谢谢!
  • 你能创建一个minimal, complete, and verifiable example吗?这意味着我们可以复制并在本地运行的代码可以演示您要解决的问题。
  • @larsks 重写了我的问题。希望现在有意义。谢谢

标签: python xml


【解决方案1】:

使用

print node.tag, node.text

而不是

print node.tag, node.attrib

对于 xml 行 &lt;Date a="b"&gt;7/18/2017 10:04:45 AM&lt;/Date&gt;
node.attrib 将输出 {'a':'b'}
node.text 将输出 '7/18/2017 10:04:45 AM'

【讨论】:

  • 真是太棒了!非常感谢!
猜你喜欢
  • 2016-07-17
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多