0
from lxml import etree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
print(ET.tostring(tree, pretty_print=True), file=open('test.xml', 'w'))

Hello, while trying to write an xml file in python with identation, I get just a one-line result. Though decoration has been set.

result:

b'<root>\n  <doc>\n    <field1 name="blah">some value1</field1>\n    <field2 name="asdfasd">some vlaue2</field2>\n  </doc>\n</root>\n'

1 Answers1

0

Your string is a byte string. You can convert it to a human readable string using the decode method. E.g:

>>> s = b'<root>\n  <doc>\n    <field1 name="blah">some value1</field1>\n    <field2 name="asdfasd">some vlaue2</field2>\n  </doc>\n</root>\n'

>>> print(s.decode())
<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some vlaue2</field2>
  </doc>
</root>

For more information about byte strings : What does the 'b' character do in front of a string literal?

If your objective is to write this string to a file, you can do so like this :

s = b'<root>\n  <doc>\n    <field1 name="blah">some value1</field1>\n    <field2 name="asdfasd">some vlaue2</field2>\n  </doc>\n</root>\n'

f = open("test.xml", "wb") # write bytes mode
f.write(s)
f.close()
SpaceBurger
  • 537
  • 2
  • 12