Search code examples
pythonxmlweb-servicestornado

How to create a class to describe the XML attribute of an element?


I am using tornado-webservices

Example XML:

<BuildingList CID=”LTP01831”>
    <Building>
        <BAID>01</BAID>
        <BAName>BuildingA</BAName>
        <UpdNo>13</UpdNo>
    </Building>
    ….
</BuildingList>

Corresponding Classes:

class Building(complextypes.ComplexType):
    BAID = str
    BAName = str
    UpdNo = str

class BuildingList(complextypes.ComplexType):
    list = [Building]

How to describe attribute "CID" in element "BuildingList" ?

Or other suggest library?


Solution

  • I assume you are only interested in xml parsing, here is a brief demo, minidom is the first python lib I used.

    from xml.dom import minidom
    
    dom = minidom.parse('test.xml')
    nodeList = dom.getElementsByTagName('BuildingList')
    cid = nodeList[0].getAttribute('CID')
    for node in nodeList:
        blist = dom.getElementsByTagName('Building')
        for bnode in blist:
            ba_id = dom.getElementsByTagName('BAID')[0].firstChild.nodeValue
            ba_name = dom.getElementsByTagName('BAName')[0].firstChild.nodeValue
            upd_no = dom.getElementsByTagName('UpdNo')[0].firstChild.nodeValue
            line = '{0} {1} {2} {3}'.format(cid, ba_id, ba_name, upd_no)
            print line
    

    ~
    The result is:

    LTP01831 01 BuildingA 13