Python Minidom:获取选定节点的所有属性?
我递归地通过Python Minidom:获取选定节点的所有属性?,python,python-2.7,xmlnode,minidom,Python,Python 2.7,Xmlnode,Minidom,我递归地通过XML中的所有节点: def verify_elements_children(root): if root.childNodes: for node in root.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName in config_elements_children[node.parentNode.tagName]:
XML
中的所有节点:
def verify_elements_children(root):
if root.childNodes:
for node in root.childNodes:
if node.nodeType == node.ELEMENT_NODE:
if node.tagName in config_elements_children[node.parentNode.tagName]:
# print node.toxml()
verify_elements_children(node)
但是我不知道如何获取所选节点的所有属性名 您只需访问属性,它是一个NamedNodeMap,您可以在该属性上调用项
,以获取字符串键和值:
import xml.dom.minidom
n = xml.dom.minidom.parseString('<n a="1" b="2" />').documentElement
attrs = dict(n.attributes.items())
assert attrs == {'a': '1', 'b': '2'}
import xml.dom.minidom
n=xml.dom.minidom.parseString(“”).documentElement
attrs=dict(n.attributes.items())
assert attrs=={a':'1',b':'2'}
我看不出这个问题与代码有什么关系。代码遍历元素,但您似乎想检查属性。@phihag我想获取当前节点的属性,而不是xml中的所有属性,因此从这个意义上讲,我想知道如何从节点
对象获取所有属性,这与我在本例中需要答案的问题有关。另一方面——目前使用mindom的情况非常普遍——如果您使用elementtree()@jsbueno每个人都推荐elementtree而不是minidom,那么您的问题可能会更容易解决,这将是下一步要完全改变它,但是我已经用MinidomThank编写了一些东西,谢谢它能工作,或者在我的例子中,node.attributes.items()中的属性值为:print attribute,value
我在minidom文档中查找,而不是dom: