Python Minidom-如何遍历属性,并获取它们的名称和值

2024-09-22 14:21:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想遍历dom节点的所有属性,并获得名称和值

我试过这样的方法(文档对此不是很详细,所以我猜了一点):

for attr in element.attributes:
    attrName = attr.name
    attrValue = attr.value
  1. for循环甚至都没有启动
  2. 一旦循环开始工作,如何获取属性的名称和值?

循环错误:

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新手,请温柔一点


Tags: 方法namein文档名称for属性节点
3条回答

有一个短而有效的(和Python?)容易做到的方法

#since items() is a tUple list, you can go as follows :
for attrName, attrValue in element.attributes.items():
    #do whatever you'd like
    print "attribute %s = %s" % (attrName, attrValue)

如果您想要实现的是将那些不方便的属性NamedNodeMap转移到一个更可用的字典中,您可以按如下步骤进行

#remember items() is a tUple list :
myDict = dict(element.attributes.items())

http://docs.python.org/2/library/stdtypes.html#mapping-types-dict 更准确的例子是:

d = dict([('two', 2), ('one', 1), ('three', 3)])

好的,在看了this (somewhat minimal) documentation之后,我猜下面的解决方案会成功

#attr is a touple apparently, and items() is a list
for attr in element.attributes.items():
    attrName = attr[0] 
    attrValue = attr[1]

属性返回一个NamedNodeMap,它的行为很像字典,但实际上不是字典。尝试在attributesiteritems()上循环。(无论如何,请记住,循环遍历常规dict循环遍历键,这样您的代码在任何情况下都不会按预期工作。)

相关问题 更多 >