Home >Backend Development >Python Tutorial >How Can I Pretty Print XML in Python?

How Can I Pretty Print XML in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 12:34:28582browse

How Can I Pretty Print XML in Python?

Pretty Printing XML in Python

In Python, there are several approaches to pretty print XML, which involves formatting the XML content for clarity and readability. One of the most straightforward methods is to use the xml.dom.minidom module.

To pretty print XML using xml.dom.minidom, follow these steps:

  1. Parse the XML:

    • Import the xml.dom.minidom module.
    • Parse the XML file or string using the parse() or parseString() function.
  2. Create a Pretty Printed XML String:

    • Call the toprettyxml() method on the DOM object representing the parsed XML.
    • This method formats the XML content, aligning tags and attributes for clarity.
import xml.dom.minidom

dom = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()

The pretty_xml_as_string variable now contains the formatted XML as a string. You can use this string for further processing or display.

The above is the detailed content of How Can I Pretty Print XML in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn