Table of Contents
How to pretty print XML in Python?
Method 1: Use xml.dom.minidom
Procedure 2: Using xml.etree.ElementTree
Option 1: Use xml.dom.minidom
Output
in conclusion
Home Backend Development Python Tutorial Pretty printing XML in Python

Pretty printing XML in Python

Sep 07, 2023 pm 07:41 PM
xml formatting python print xml Present xml beautifully

Pretty printing XML in Python

When working with XML data in Python, ensuring its readability and structure can greatly enhance the understanding and maintainability of your code. Pretty-printing XML, that is, formatting it with appropriate indentation and newlines, is a valuable technique for achieving these goals.

In this article, we'll explore two different ways to pretty-print XML using Python: xml.dom.minidom and xml.etree.ElementTree. By understanding these methods, developers can effectively present XML data in an organized and visually appealing way, making it easier to analyze and manipulate.

How to pretty print XML in Python?

Here are two ways we can perform pretty printing in Python -

Method 1: Use xml.dom.minidom

Here are the steps we will take to perform pretty printing using xml.dom.minidom -

  • Import the required modules: We first import the "xml.dom.minidom" module, which provides a lightweight implementation of the Document Object Model (DOM) API for XML parsing.

  • Define the `pretty_print_xml_minidom` function: This function accepts an XML string as input and is responsible for parsing and beautifying the XML for printing using `xml.dom.minidom`.

  • Parse XML string: Inside the `pretty_print_xml_minidom` function, we use the `xml.dom.minidom.parseString()` method to parse the XML string and create a DOM object.

  • Pretty-printing XML: Next, we use the "toprettyxml()" method on the DOM object to generate a pretty-printing XML string. We pass the "indent" parameter with the value """ to specify the desired indentation level (two spaces in this case).

  • Remove blank lines: By default, `toprettyxml()` adds blank lines to the output. To remove these empty lines, we split the pretty XML string with newlines (`\n`), remove any leading or trailing whitespace in each line, and then concatenate the non-empty lines back together.

  • Print pretty XML: Finally, we print the generated pretty XML string.

Procedure 2: Using xml.etree.ElementTree

Here are the steps we will follow to perform pretty printing using xml.etree.ElementTree -

  • Import the required modules: We first import the `xml.etree.ElementTree` module, which provides a fast and efficient API for parsing and manipulating XML.

  • Definition`indent` Function: This is a custom function used to recursively add indents to XML elements. It accepts an `elem` parameter (XML element) and an optional `level` parameter to specify the current indentation level (default is 0).

  • Indent XML: In the `indent` function, we add indent > XML by modifying `text` and `tail` The element's properties. The `text` attribute represents the text immediately after the opening tag, and the `tail` attribute represents the text immediately before the closing tag. By adding indentation to these properties, we achieve pretty printing.

  • Definition `pretty_print_xml_elementtree` Function: This function takes an XML string as input and is responsible for parsing and pretty-printing the XML using `xml.etree.ElementTree`.

  • Parsing XML string: Inside the `pretty_print_xml_elementtree` function, we use the `ET.fromstring()` method to parse the XML string and create an ElementTree object.

  • Indent XML: We call the `indent()` function on the root element of the XML to add indentation to all elements recursively.

  • Convert XML elements back to strings: We use the `ET.tostring()` method to convert XML elements back to string representation. We pass the `encoding` parameter with the value `"unicode"` to ensure the correct encoding of the resulting string.

  • Print pretty XML: Finally, we print the generated pretty XML string.

These two programs provide different methods to achieve pretty printing of XML. The first program utilizes the DOM API provided by `xml.dom.minidom` to parse and pretty print XML, while the second program uses the `xml.etree.ElementTree` module, And defined a custom function to add indentation to XML elements recursively.

The following are program examples using the above two methods -

Option 1: Use xml.dom.minidom

import xml.dom.minidom

def pretty_print_xml_minidom(xml_string):
   # Parse the XML string
   dom = xml.dom.minidom.parseString(xml_string)

   # Pretty print the XML
   pretty_xml = dom.toprettyxml(indent="  ")

   # Remove empty lines
   pretty_xml = "\n".join(line for line in pretty_xml.split("\n") if line.strip())

   # Print the pretty XML
   print(pretty_xml)

# Example usage
xml_string = '''
<root>
  <element attribute="value">
   <subelement>Text</subelement>
  </element>
</root>
'''

pretty_print_xml_minidom(xml_string)
Copy after login

Output

<?xml version="1.0" ?>
<root>
  <element attribute="value">
   <subelement>Text</subelement>
  </element>
</root>
Copy after login

Procedure 2: Using xml.etree.ElementTree

import xml.etree.ElementTree as ET

def indent(elem, level=0):
   # Add indentation
   indent_size = "  "
   i = "\n" + level * indent_size
   if len(elem):
      if not elem.text or not elem.text.strip():
         elem.text = i + indent_size
      if not elem.tail or not elem.tail.strip():
         elem.tail = i
      for elem in elem:
         indent(elem, level + 1)
      if not elem.tail or not elem.tail.strip():
         elem.tail = i
   else:
      if level and (not elem.tail or not elem.tail.strip()):
         elem.tail = i

def pretty_print_xml_elementtree(xml_string):
   # Parse the XML string
   root = ET.fromstring(xml_string)

   # Indent the XML
   indent(root)

   # Convert the XML element back to a string
   pretty_xml = ET.tostring(root, encoding="unicode")

   # Print the pretty XML
   print(pretty_xml)

# Example usage
xml_string = '''
<root>
  <element attribute="value">
   <subelement>Text</subelement>
  </element>
</root>
'''

pretty_print_xml_elementtree(xml_string)
Copy after login

Output

<root>
  <element attribute="value">
   <subelement>Text</subelement>
  </element>
</root>
Copy after login

in conclusion

In summary, pretty-printing XML in Python is crucial to improving the readability and structure of your XML data. Whether using the xml.dom.minidom or xml.etree.ElementTree libraries, developers can easily format XML with proper indentation. By employing these techniques, programmers can enhance code understanding, simplify debugging, and promote better collaboration when working with XML data in Python projects.

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

See all articles