minidom解析xml 小试一篇

#!/usr/bin/env python
#coding=utf-8
from xml.dom import minidom

class Xml_dom():
    def readNodes(self,domElement):
        for nodes in domElement.childNodes:
            if nodes.nodeType == 1:
                print nodes.nodeName+'====================='
                for keys in nodes.attributes.keys():
                    print nodes.attributes[keys].name+'='+nodes.attributes[keys].value
                    if len(nodes.childNodes)==1:
                        print nodes.nodeName+':'+nodes.childNodes[0].nodeValue
                    else:
                        self.readNodes(nodes)
    def readElementByName(self,elementList):
        for elements in elementList:
            if elements.nodeType == 1:
                print elements.nodeName+'>>>>>>>>>>>>>>>>>>>>>>>'
                for keys in elements.attributes.keys():
                    print elements.attributes[keys].name+'='+elements.attributes[keys].value
            if len(elements.childNodes) == 1:
                print elements.nodeName+':'+elements.childNodes[0].nodeValue
            else:
                self.readElementByName(elements.childNodes)
    def __init__(self,filename,elename):
        self.dom = minidom.parse(filename)
        self.root = self.dom.documentElement
        print '=========xml_dom==============\n'
        self.readNodes(self.root)
        print '=========end===============\n'
        print '>>>>>>>>>xml_dom>>>>>>>>>>\n'
        el = self.dom.getElementsByTagName(elename)
        self.readElementByName(el)
        print ">>>>>>>>>end>>>>>>>>>>>>"
        
if __name__=='__main__':
#    a = Xml_dom('rule_sqlInj.xml','configs')
    a = Xml_dom('waf_sqlrule.xml','prot')

 得到的结果为

写道
> "D:\Python25\pythonw.exe" -u "D:\学习\python\xml\xml_dom\xml_dom.py"
=========xml_dom==============

policy=====================
prot=====================
other=====================
test_case_id=1
action=====================
res=====================
rule=====================
ID=18612269
value=\x22
=========end===============

>>>>>>>>>xml_dom>>>>>>>>>>

prot>>>>>>>>>>>>>>>>>>>>>>>
dstip>>>>>>>>>>>>>>>>>>>>>>>
dstip:2.2.2.2
dstip>>>>>>>>>>>>>>>>>>>>>>>
dstip:3.3.3.3
dstport>>>>>>>>>>>>>>>>>>>>>>>
dstport:80
srcip>>>>>>>>>>>>>>>>>>>>>>>
srcip:3.3.3.3
srcport>>>>>>>>>>>>>>>>>>>>>>>
srcport:8888
protocol>>>>>>>>>>>>>>>>>>>>>>>
protocol:17
>>>>>>>>>end>>>>>>>>>>>>

 

你可能感兴趣的:(xml,python)