Python ElementTree found not working

Python ElementTree found not working … here is a solution to the problem.

Python ElementTree found not working

I’m new to ElementTree. I’m trying to get the value of the <sid > from an XML response.

The following code doesn’t work for me. How do I extract values from <sid>? I’m not sure where the number 53 came from.

    ...
    r = requests.post(self.dispatchurl, verify=False, auth=HTTPBasicAuth(self.user, self.passwd))
    print r.content
    tree = ET. ElementTree(r.content)
    print tree.find('sid')

Output:

/usr/bin/python2.7 /home/myuser/PycharmProjects/autoshun/shunlibs/SplunkSearch.py
<?xml version="1.0" encoding="UTF-8"?>
<response>
  <sid>super__awesome__search__searchname_at_1489433276_24700</sid>
</response>

53

Process finished with exit code 0

Solution

I

know the OP is almost 2 years old but I had the same problem and found a solution that worked for me. An effective approach is to delete the namespace immediately after the parse call to load the XML file.

Functions like this:

def remove_namespace(xmldoc, namespace):
    ns = u'{%s}' % namespace
    nsl = len(ns)
    for elem in xmldoc.getiterator():
        if elem.tag.startswith(ns):
            elem.tag = elem.tag[nsl:]

I found that ElementTree has a namespace issue, and you either remove it using the above function or have to pass an explicit namespace to the find or findall function.

Related Problems and Solutions