Read XML through Python

0

I need to get data in an XML file from another domain, initially I did a js, I had to abort.

I thought about reading the files through .py within my Django project In test character I tried something else one less like this:

tree = ET.ElementTree(file=urllib2.urlopen('http://192.168.2.57:8010/data/camera_state.xml'))
root = tree.getroot()
root.tag, root.attrib

for elem in tree.iter():
    print elem.tag, elem.att

I could not get into the structure I needed, the way out of my test.py, this looks something like this:

CameraState {}
Cameras {}
Camera {'Id': '1'}
State {}
Camera {'Id': '2'}
State {}
Camera {'Id': '3'}
State {}
Camera {'Id': '4'}
State {}

This is the XML structure on the external server, how can I extract the data using ElementTree to get to this original structure? below

<CameraState>
    <Cameras>
        <Camera Id="1">
            <State>NO_SIGNAL</State>
        </Camera>

        <Camera Id="2">
            <State>OK</State>
        </Camera>
    </Cameras>
</CameraState>

I need to get this data to later save this information to a table, but that part is quiet.

Embrace

    
asked by anonymous 09.11.2017 / 22:14

1 answer

2

Root is already in the structure you want, it is a linked list, but if you use iter (), the result will be all elements. if you want the hierarchy, go through it as a hierarchy:

print(root.tag,":")
for cameras in root:
    print("---|",cameras.tag,":")
    for camera in cameras:
        print("---|---|",camera.tag,":", camera.attrib)
        for state in camera:
            print("---|---|---|",state.tag,":", state.text)

The output will be:

CameraState :
---| Cameras :
---|---| Camera : {'Id': '1'}
---|---|---| State : NO_SIGNAL
---|---| Camera : {'Id': '2'}
---|---|---| State : OK
    
10.11.2017 / 16:01