XML.SAX XML读取写入
读取简单的xml,并写入。只支持单列的内容,处理结果,写入输入都是map
<xml>
<input_file>VERYGOOD</input_file>
<outpuf_folder>VERYBAD</outpuf_folder>
</xml>
import xml
from xml import sax
config_map = {}
class ConfigHandler(xml.sax.ContentHandler): #继承于xml.sax.ContentHandler类
def __init__(self):
self.data = ""
def startElement(self, tag, attr):
pass
def characters(self, content):
self.data = content
def endElement(self, tag):
#if tag != "config":
if self.data.strip() != '':
config_map[tag.lower()] = self.data
def endDocument(self):
pass
class XMLParser():
def __init__(self):
config_map = {}
self.parser = sax.make_parser()
self.parser.setFeature(xml.sax.handler.feature_namespaces,0)
Handler = ConfigHandler()
self.parser.setContentHandler( Handler )
def read(self,xmlpath):
config_map.clear()
self.parser.parse(xmlpath)
return config_map
def write(self,xmlpath,xml_map):
with open(xmlpath,'w') as f:
f.write('<xml>\n')
for i in xml_map:
f.write('<'+i+'>'+xml_map[i]+'</'+i+'>\n')
f.write('</xml>\n')
f.close()
def test(self):
self.read('config.xml')
for i in config_map:
print(i + ":" + str(config_map[i]))
self.write('out.xml',config_map)
#x = XMLParser()
#x.test()