我正在尝试解析带有命名空间的 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/