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]

你可能感兴趣的:(python)