zoukankan      html  css  js  c++  java
  • python 读取xml文档

    原文地址:http://www.cnblogs.com/lgcf/archive/2009/09/25/1573863.html

    test.py

    from xml.dom.minidom import parse,parseString
    class XmlConfig:
    def __init__(self,path):
    self.xmlData=self.GetXml(path)
    def GetText(self,nodelist):
    r=""
    for nxd in nd.childNodes:
    r=r+nxd.nodeValue
    return r
    def GetXml(self,path):
    doc=parse(path)
    st=doc.firstChild
    websites= st.childNodes

    lstList=[]
    for sw in websites:
    if sw.nodeType==sw.ELEMENT_NODE :
    lsty=[]
    for nd in sw.childNodes:
    if nd.nodeType==nd.ELEMENT_NODE:
    ndName= nd.nodeName
    ndValue= nd.firstChild.data
    b=(ndName,ndValue)
    lsty.append(b)
    lstList.append(lsty)
    return lstList

    def GetSingle(self,siteName):
    for item in self.xmlData:
    for k,v in item:
    if v==siteName:
    return item

    def GetSingleDict(self,siteName):
    lst=self.GetSingle(siteName)
    dic={}
    if len(lst)>0:
    for item in lst:
    dic[item[0]]=item[1]
    return dic

    if __name__=="__main__":
    f=XmlConfig("test.xml")
    print f.xmlData

    test.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <Site>
    <WebSites>
    <website>http://www.xxx.net</website>
    <loginurl>http:///www.xxx.net/login.php</loginurl>
    <username>uname=xxx</username>
    <passwd>pass=123456</passwd>
    <other><![CDATA[r=5&remember=0&ur=xxx]]></other>
    <config>WebSite.ini</config>
    <configname>XXX</configname>
    </WebSites>
    <WebSites>
    <website>http://www.xxx.com</website>
    <loginurl>http:///www.xxx.com/login.php</loginurl>
    <username>uname=xxx</username>
    <passwd>pass=123456</passwd>
    <other><![CDATA[r=5&remember=0&ur=xxx]]></other>
    <config>WebSite.ini</config>
    <configname>XXX</configname>
    </WebSites>
    </Site>

    结果:

    m@m-desktop:~/.wkl/a$ python test.py 
    [[(u'website', u'http://www.xxx.net'), (u'loginurl', u'http:///www.xxx.net/login.php'), (u'username', u'uname=xxx'), (u'passwd', u'pass=123456'), (u'other', u'r=5&remember=0&ur=xxx'), (u'config', u'WebSite.ini'), (u'configname', u'XXX')], [(u'website', u'http://www.xxx.com'), (u'loginurl', u'http:///www.xxx.com/login.php'), (u'username', u'uname=xxx'), (u'passwd', u'pass=123456'), (u'other', u'r=5&remember=0&ur=xxx'), (u'config', u'WebSite.ini'), (u'configname', u'XXX')]]







  • 相关阅读:
    14 break
    13 for循环
    Python 3.7 将引入 dataclass 装饰器
    工程师如何在面试中脱颖而出
    如何避免 async/await 地狱
    命令行里打 cd 简直是浪费生命
    GitHub 十大 CI 工具
    GitHub CEO:GitHub 十年,感谢有你
    如何在 2 分钟内入睡(二战时期美国飞行员训练法)
    一分钟了解 TCP/IP 模型
  • 原文地址:https://www.cnblogs.com/wangkangluo1/p/2186460.html
Copyright © 2011-2022 走看看