zoukankan      html  css  js  c++  java
  • Python解析XML

    #!/bin/python
    #
    coding=utf-8

    import xml.dom.minidom
    from collections import defaultdict

    class Configure:


    def __init__(self, file):
    self.params = {}
    self.configs = []
    self.lists = ['list', 'map', 'tuple']
    self.configFile = file
    self.parseAll()


    def parseAll(self):
    dom = xml.dom.minidom.parse(self.configFile)
    root = dom.documentElement
    self.parseConfig(root.getElementsByTagName("config"))


    def parseConfig(self, configs):

    for configNode in configs:
    id = configNode.attributes['id'].value
    self.params[id] = {}

    propertyNodes = configNode.getElementsByTagName('property')
    for propertyNode in propertyNodes:
    name = propertyNode.attributes['name'].value
    type = propertyNode.attributes['type'].value

    value = None
    if propertyNode.hasAttribute('value'):
    value = propertyNode.attributes['value'].value

    self.params[id][name] = value

    if not type in self.lists: continue
    items = propertyNode.getElementsByTagName('item')
    if type == "list":
    value = [item.attributes['value'].value for item in items]

    if type == "map":
    value = {}
    for item in items:
    key = item.attributes['index'].value
    val = item.attributes['value'].value
    value[key] = val

    self.params[id][name] = value

    def get(self, name, index, default=None):
    if not self.params.has_key(index): return default
    if not self.params[index].has_key(name): return default
    return self.params[index][name]
  • 相关阅读:
    勤于思考,善于总结,积极进取,认识自己
    notepad++中cmd运行中文乱码?
    notpad++使用cmd的快捷键设置
    深刻理解Table以及关于table的插件(1)
    单向链表
    apriori算法
    保存一个班级的学生信息
    测试list列表中append和insert的执行速度
    二分查找
    顺序查找法
  • 原文地址:https://www.cnblogs.com/rilley/p/2334337.html
Copyright © 2011-2022 走看看