How to output XML in a good way?

Asked 2 years ago, Updated 2 years ago, 112 views

How can I print out the xml beautifully?

There is an xml file like this

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

When running Python code

import xml.dom.minidom

xml = xml.dom.minidom.parse("myxml.xml")
pretty_xml_as_string = xml.toprettyxml()
print(pretty_xml_as_string)

Result:

<?xml version="1.0" ?>
<foo>


    <bar>


        <type foobar="1"/>


        <type foobar="2"/>


    </bar>


</foo>

There are too many indentations.

xml python pretty-print

2022-09-21 17:11

1 Answers

lxml.etree.parse outputs the xml file itself without opening.

import lxml.etree as etree

x = etree.parse("myxml.xml")
print etree.tostring(x, pretty_print = True)

Result:

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>


2022-09-21 17:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.