Era*_*dan 8 python minidom python-3.x
我想遍历dom节点的所有属性并获取名称和值
我试过这样的事情(文档对此并不是很冗长,所以我猜了一下):
for attr in element.attributes:
attrName = attr.name
attrValue = attr.value
Run Code Online (Sandbox Code Playgroud)
循环错误:
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
Run Code Online (Sandbox Code Playgroud)
我是Python新手,请温柔
Ar3*_*r3s 13
有一种简短而有效(和pythonic?)的方式可以轻松完成
#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)
Run Code Online (Sandbox Code Playgroud)
如果您要实现的目的是将这些不方便的属性转移NamedNodeMap到更可用的字典,您可以按照以下步骤操作
#remember items() is a tUple list :
myDict = dict(element.attributes.items())
Run Code Online (Sandbox Code Playgroud)
请参阅http://docs.python.org/2/library/stdtypes.html#mapping-types-dict ,更准确地说是示例:
d = dict([('two', 2), ('one', 1), ('three', 3)])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13829 次 |
| 最近记录: |