我在包含xml的数据库中有很多行,我正在尝试编写一个Python脚本,该脚本将遍历这些行并计算特定节点属性的实例数量.例如,我的树看起来像:
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
Run Code Online (Sandbox Code Playgroud)
如何使用Python访问XML中的属性1和2?
我目前正在根据Python Cookbook的第12.5章运行以下代码:
from xml.parsers import expat
class Element(object):
def __init__(self, name, attributes):
self.name = name
self.attributes = attributes
self.cdata = ''
self.children = []
def addChild(self, element):
self.children.append(element)
def getAttribute(self,key):
return self.attributes.get(key)
def getData(self):
return self.cdata
def getElements(self, name=''):
if name:
return [c for c in self.children if c.name == name]
else:
return list(self.children)
class Xml2Obj(object):
def __init__(self):
self.root = None
self.nodeStack = []
def StartElement(self, name, attributes):
element = Element(name.encode(), attributes)
if self.nodeStack:
parent = self.nodeStack[-1]
parent.addChild(element)
else:
self.root …Run Code Online (Sandbox Code Playgroud)