Read XML via Python

Asked

Viewed 1,055 times

0

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

I thought of reading the files through . py within my Django project I tried something a little 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 couldn’t get to the structure I needed, the way out of my test.py, it’s kind of 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 that 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 in a table, but this part is quiet.

Hug

  • apparently, what the iter() function does traverses through all the elements, and the output really is what you had. the structure is right. If you want only the children of the Camerastate, and do not go through all the elements, do without the iter():for elem in Tree:

1 answer

2

root is already in the structure you want, it’s a chained list, but if Voce uses iter(), the result will be all elements. if you want the hierarchy, then 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 exit will be:

CameraState :
---| Cameras :
---|---| Camera : {'Id': '1'}
---|---|---| State : NO_SIGNAL
---|---| Camera : {'Id': '2'}
---|---|---| State : OK

Browser other questions tagged

You are not signed in. Login or sign up in order to post.