Python 中 XML 的漂亮列印


在 Python 中處理 XML 資料時,確保其可讀性和結構可以極大地增強程式碼理解和可維護性。XML 的漂亮列印,或者使用適當的縮排和換行符對其進行格式化,是實現這些目標的寶貴技術。

在本文中,我們探討了使用 Python 對 XML 進行漂亮列印的兩種不同方法:xml.dom.minidom 和 xml.etree.ElementTree。通過了解這些方法,開發人員可以有效地以組織化和視覺上吸引人的方式呈現 XML 資料,從而促進更輕鬆的分析和操作。

如何在 Python 中進行 XML 漂亮列印?

以下是我們可以使用兩種方法在 Python 中執行漂亮列印的方法:

方法 1:使用 xml.dom.minidom

以下是我們將遵循使用 xml.dom.minidom 執行漂亮列印的步驟:

  • 匯入所需的模組:我們首先匯入 `xml.dom.minidom` 模組,該模組為 XML 解析提供了輕量級的文件物件模型 (DOM) API 實現。

  • 定義 `pretty_print_xml_minidom` 函式:此函式以 XML 字串作為輸入,並負責使用 `xml.dom.minidom` 解析和漂亮列印 XML。

  • 解析 XML 字串:在 `pretty_print_xml_minidom` 函式內部,我們使用 `xml.dom.minidom.parseString()` 方法解析 XML 字串並建立 DOM 物件。

  • 漂亮列印 XML:接下來,我們對 DOM 物件使用 `toprettyxml()` 方法來生成漂亮列印的 XML 字串。我們將 `indent` 引數的值傳遞為 `" "` 以指定所需的縮排級別(在本例中為兩個空格)。

  • 刪除空行:預設情況下,`toprettyxml()` 會在輸出中新增空行。為了刪除這些空行,我們將漂亮的 XML 字串按換行符 (`\n`) 分割,刪除每行開頭的或結尾的空格,然後將非空行重新連線在一起。

  • 列印漂亮的 XML:最後,我們列印生成的漂亮 XML 字串。

程式 2:使用 xml.etree.ElementTree

以下是我們將遵循使用 xml.etree.ElementTree 執行漂亮列印的步驟:

  • 匯入所需的模組:我們首先匯入 `xml.etree.ElementTree` 模組,該模組提供了一個快速有效的 API 用於解析和操作 XML。

  • 定義 `indent` 函式:這是一個自定義函式,它遞迴地向 XML 元素新增縮排。它接收一個 `elem` 引數(XML 元素)和一個可選的 `level` 引數來指定當前縮排級別(預設為 0)。

  • 縮排 XML:在 `indent` 函式內部,我們透過修改 XML 元素的 `text``tail` 屬性來新增縮排。`text` 屬性表示開始標籤後的文字,`tail` 屬性表示結束標籤前的文字。透過向這些屬性新增縮排,我們實現了漂亮列印。

  • 定義 `pretty_print_xml_elementtree` 函式:此函式以 XML 字串作為輸入,並負責使用 `xml.etree.ElementTree` 解析和漂亮列印 XML。

  • 解析 XML 字串:在 `pretty_print_xml_elementtree` 函式內部,我們使用 `ET.fromstring()` 方法解析 XML 字串並建立 ElementTree 物件。

  • 縮排 XML:我們對 XML 的根元素呼叫 `indent()` 函式,以遞迴地向所有元素新增縮排。

  • 將 XML 元素轉換回字串:我們使用 `ET.tostring()` 方法將 XML 元素轉換回字串表示形式。我們將 `encoding` 引數的值傳遞為 `"unicode"` 以確保生成的字串正確編碼。

  • 列印漂亮的 XML:最後,我們列印生成的漂亮 XML 字串。

這兩個程式都提供了不同的方法來實現 XML 的漂亮列印。第一個程式利用 `xml.dom.minidom` 提供的 DOM API 來解析和漂亮列印 XML,而第二個程式使用 `xml.etree.ElementTree` 模組並定義了一個自定義函式來遞迴地向 XML 元素新增縮排。

以下是使用上述兩種方法的程式示例:

程式 1:使用 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)

輸出

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

程式 2:使用 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)

輸出

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

結論

總之,在 Python 中對 XML 進行漂亮列印對於提高 XML 資料的可讀性和結構至關重要。無論使用 xml.dom.minidom 還是 xml.etree.ElementTree 庫,開發人員都可以輕鬆地使用正確的縮排格式化 XML。透過採用這些技術,程式設計師可以增強程式碼理解,簡化除錯,並在 Python 專案中使用 XML 資料時促進更好的協作。

更新於: 2023-07-25

7K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告