search
HomeBackend DevelopmentPython TutorialPretty printing XML in Python

Pretty printing XML in Python

Sep 07, 2023 pm 07:41 PM
xml formattingpython print xmlPresent 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)

Output

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

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)

Output

<root>
  <element attribute="value">
   <subelement>Text</subelement>
  </element>
</root>

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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

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 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...

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software