我想遍历dom节点的所有属性,并获得名称和值
我试过这样的方法(文档对此不是很详细,所以我猜了一点):
for attr in element.attributes:
attrName = attr.name
attrValue = attr.value
循环错误:
for attr in element.attributes:
File "C:\Python32\lib\xml\dom\minidom.py", line 553, in __getitem__
return self._attrs[attname_or_tuple]
KeyError: 0
我是Python新手,请温柔一点
有一个短而有效的(和Python?)容易做到的方法
如果您想要实现的是将那些不方便的属性
NamedNodeMap
转移到一个更可用的字典中,您可以按如下步骤进行见http://docs.python.org/2/library/stdtypes.html#mapping-types-dict 更准确的例子是:
好的,在看了this (somewhat minimal) documentation之后,我猜下面的解决方案会成功
属性返回一个
NamedNodeMap
,它的行为很像字典,但实际上不是字典。尝试在attributes
的iteritems()
上循环。(无论如何,请记住,循环遍历常规dict循环遍历键,这样您的代码在任何情况下都不会按预期工作。)相关问题 更多 >
编程相关推荐