【问题标题】:Python XML getting all tags of name "X"Python XML获取名称“X”的所有标签
【发布时间】:2018-03-23 17:10:56
【问题描述】:

我有一个类似于以下内容的 XML 文件:

<a>
   <b>
       <c>
       </c>
   </b>
   <d>
       <e>
           <f>Value</f>    <!-- I want to extract this -->
       </e>
   </d>
   <d>
       <e>
           <f>Value2</f>   <!-- and this -->
       </e>
   </d>
   .
   .
   .

我正在尝试使用以下 Python 代码从节点中检索所有数据,即 Value1、Value2 .....我的理解是否正确?

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')

for elem in tree.iterfind('a/d/e/f'):
     print(elem.tag, elem.attrib)

但是,我只是得到一个空循环。我也尝试使用在线示例 findall() 但无济于事。我只是想验证我是否正确理解了他们的能力。

【问题讨论】:

  • 如果你把那个 XML 片段变成一个完整的文档(这可能只是在最后添加 &lt;/a&gt; 的问题),这将更容易调试。更好的是,将 XML 放在源代码中的字符串中并更改您的示例以使用它而不是文件,然后您将拥有完美的 minimal reproducible example。

标签: python xml elementtree


【解决方案1】:

这里的问题是您的 XPath 开始在根下寻找 a 子节点,但根是 a 节点,b 和 d节点是它的孩子。

如果你只是打印出来,你可以看到这个:

>>> print(tree)
<Element 'a' at 0x10bbe4bd8>
>>> print(tree.getchildren())
[<Element 'b' at 0x10bf8e318>,
 <Element 'd' at 0x10bf8ef98>,
 <Element 'd' at 0x10be1e818>]

你可能想要的是这个:

for elem in tree.iterfind('d/e/f'):

或者,正如 Tim 在 cmets 中指出的那样,如果您的 tree 是解析文件而不是树的根的结果,那么您需要这样做:

root = tree.getroot()
for elem in root.iterfind(‘d/e’f’):

【讨论】:

  • 我正在获取 Traceback(最近一次调用最后一次):文件“”,第 1 行,在 print(tree.getchildren()) AttributeError: 'ElementTree' object没有属性“getchildren”
  • @user997112 这正是minimal reproducible example 很重要的原因。它在我通过猜测您的代码在做什么创建的示例中有效,但我显然猜错了。
  • 您的 Traceback 的问题是 ElementTree 对象没有孩子,但 Element 对象有。所以你需要构建树然后获取根元素以使用getchildren()。我想 abarnert 正在使用 tree = ET.fromstring(...) 来构建树并返回根元素,而 user997112 正在使用 tree = ET.parse('file.xml')。你真的应该这样做:root = ET.fromstring(xml_file_as_a_string) 或:tree = ET.parse('file.xml') 然后root = tree.getroot()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 2022-11-25
  • 2020-11-19
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多