python - AttributeError: 'Element' 对象没有属性 'findAll'

标签 python xml namespaces attributeerror findall

我正在尝试解析带有命名空间的 XML, XML 看起来像

<DATA xmlns="http://example.com/nspace/DATA/1.0"  xmlns:UP="http://example.com/nspace/UP/1.1" col_time_us="14245034321452862">
<UP:IN>...</UP:IN>
<UP:ROW>
     <sampleField>...</sampleField>                
</UP:ROW>
<UP:ROW>
     <sampleField>...</sampleField>                
</UP:ROW>
.
. 
.
</DATA>

当我使用下面的代码解析XML时

tree=ET.parse(fileToParse);
root=tree.getRoot();
namespaces = {'UP':'http://example.com/nspace/DATA/1.0'}
for data in root.findAll('UP:ROW',namespaces):
        hour+=1

我收到以下错误:

AttributeError: 'Element' object has no attribute 'findAll'

当我尝试遍历 root 的子项并打印标签时,我得到 {http://example.com/nspace/DATA/1.0}ROW 而不仅仅是 ROWS .

我想找到 ROW 元素并提取 sampleField 标记的值。任何人都可以指导我我可能做错了什么吗?

最佳答案

ElementTree Element 对象确实没有 findAll() 方法。正确的使用方法是Element.findall() , 全部小写。

您还为 UP 命名空间使用了错误的命名空间 URI。根元素定义了两个命名空间,您需要选择第二个:

<DATA xmlns="http://example.com/nspace/DATA/1.0"  
      xmlns:UP="http://example.com/nspace/UP/1.1" ...>

注意 xmlns:UP,因此使用该 URI:

>>> namespaces = {'UP': 'http://example.com/nspace/UP/1.1'}
>>> root.findall('UP:ROW', namespaces)
[<Element {http://example.com/nspace/UP/1.1}ROW at 0x102eea248>, <Element {http://example.com/nspace/UP/1.1}ROW at 0x102eead88>]

关于python - AttributeError: 'Element' 对象没有属性 'findAll',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29565040/

相关文章:

python - 为什么 `eval` 在 Python 类函数中不起作用?

asp.net - ajaxtoolkit :CalendarExtender working on one asp. 网络网页,但不在同一站点的其他网页上

python - 使用 Pygit2 实现拉取

python - 如何在从 "tablib"生成的 XLS 文件中为每个数据表添加工作表名称?

javascript - 使用 javascript 从单选按钮获取值

python - Django:当本地 .py 文件更改并动态加载时,有没有办法防止开发服务器重新启动?

java - 什么是最简单和简约的 java xml api?

php - S3 URL 中带双引号的文件名会导致参数无效

java - Java 中用于获取 xml 元素的 XPath 表达式

PHP 命名空间和单例问题