相关疑难解决方法(0)

如何在Python中解析XML?

我在包含xml的数据库中有很多行,我正在尝试编写一个Python脚本,该脚本将遍历这些行并计算特定节点属性的实例数量.例如,我的树看起来像:

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>
Run Code Online (Sandbox Code Playgroud)

如何使用Python访问XML中的属性1和2?

python xml

938
推荐指数
15
解决办法
117万
查看次数

在Python中解析大型XML文档的最快方法是什么?

我目前正在根据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)

python xml performance parsing

57
推荐指数
5
解决办法
6万
查看次数

标签 统计

python ×2

xml ×2

parsing ×1

performance ×1