gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:42:44 27 4
gpt4 key购买 nike

我想遍历一个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 新手,请温柔点

最佳答案

有一种简短而有效(和 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)

如果您想要实现的是将那些不方便的属性 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)])

关于Python Minidom - 如何遍历属性,并获取它们的名称和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11654669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com