0

I have a small script that makes requests with httplib2 which returns the response body as bytes. I normally want to immediately decode it to str so that my code can work as it previously did with 2.7.

However, when the response is XML with encoding as the first line, lxml.objectify fails in python 3 as it expects bytes not str. What is the best way to go from XML str to a objectified object in Python 3?

user7692855
  • 1,582
  • 5
  • 19
  • 39

1 Answers1

0

To parse xml from a string using lxml, you can use .fromstring() method.

Example:

from lxml import etree

xml = '<a xmlns="test"><b xmlns="test"/></a>'

root = etree.fromstring(xml)
Rithin Chalumuri
  • 1,739
  • 7
  • 19
  • Sorry I should have been clearer that doesn't work. I had a check (which I should have done first and it looks like it's not a clean solution). https://stackoverflow.com/questions/15830421/xml-unicode-strings-with-encoding-declaration-are-not-supported – user7692855 Nov 03 '19 at 16:14
  • 3
    @user7692855, could you update the question to incldue the code you've tried/response you get/any errors? so it's minimal reproducible. https://stackoverflow.com/help/minimal-reproducible-example – Rithin Chalumuri Nov 03 '19 at 16:16