1

I would like to read an xml file then convert it to a string.

I tried the following:

et = ET.parse('file.xsd')
xml_str = ET.tostring(et, encoding='unicode')

But I'm getting the following error:

LookupError: unknown encoding: unicode
3
  • Does this answer your question? Converting a Python XML ElementTree to a String Commented Nov 22, 2022 at 10:58
  • What package are you using? Are you using Python 2 or 3 ? Commented Nov 22, 2022 at 10:59
  • Python 2.7 im using xml.etree.ElementTree Commented Nov 22, 2022 at 11:00

1 Answer 1

1

Try:

xml_str = ET.tostring(et, encoding='utf-8')

or:

xml_str = ET.tostring(et).decode()

or

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import tostring

tree = ET.parse('file.xsd')
tree = tree.getroot()

xml_str = tostring(tree)
xml_str = xml_str.lower()
tree= ET.fromstring(xml_str)

Sign up to request clarification or add additional context in comments.

3 Comments

tried both. im getting the same error: 'ElementTree' object has no attribute 'tag'
yes............
Ok - last try - try the third option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.