【问题标题】:AttributeError: 'Element' object has no attribute 'findAll'AttributeError:“元素”对象没有属性“findAll”
【发布时间】:2015-04-10 15:17:47
【问题描述】:

我正在尝试使用命名空间解析 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 标记的值。有人可以指导我做错什么吗?

【问题讨论】:

    标签: python xml namespaces attributeerror findall


    【解决方案1】:

    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>]
    

    【讨论】:

      猜你喜欢
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2021-07-30
      • 2013-07-29
      相关资源
      最近更新 更多