AttributeError:“Element”对象没有属性“findAll”

RAS*_*GLE 4 python xml namespaces findall attributeerror

我正在尝试使用命名空间解析 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>
Run Code Online (Sandbox Code Playgroud)

当我使用下面的代码来解析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
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

AttributeError: 'Element' object has no attribute 'findAll'
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*ers 6

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

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

<DATA xmlns="http://example.com/nspace/DATA/1.0"  
      xmlns:UP="http://example.com/nspace/UP/1.1" ...>
Run Code Online (Sandbox Code Playgroud)

请注意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>]
Run Code Online (Sandbox Code Playgroud)