使用 Python ElementTree 生成 xml
生活随笔
收集整理的這篇文章主要介紹了
使用 Python ElementTree 生成 xml
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python 處理 xml 文檔的方法有很多,除了經典的 sax 和 dom 之外,還有一個 ElementTree。
首先 import 之:
| 1 | from xml.etree import ElementTree as etree |
然后開始構建 xml 樹:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from xml.etree.ElementTree import Element, SubElement, ElementTree # 生成根節點 root = Element('root') # 生成第一個子節點 head head = SubElement(root, 'head') # head 節點的子節點 title = SubElement(head, 'title') title.text = 'Well Dola!' # 生成 root 的第二個子節點 body body = SubElement(root, 'body') # body 的內容 body.text = 'I love Dola!' tree = ElementTree(root) |
這樣就得到了一個 xml 樹的對象 tree 以及它的根節點的對象 root
接著我們把它們變成 xml 串,有兩個辦法,一個是用 tree 對象的 write 方法將 xml 內容寫成一個文件,還有一個是用 etree 的 tostring 方法轉成 xml 字符串:
| 1 2 3 4 5 | # 第一種 tree.write('result.xml', encoding='utf-8') # 第二種 xml_string = etree.tostring(root) # xml_string 就是 xml 字符串了 |
但是第二種有一個問題,就是它沒有
| 1 | <?xml version="1.0"?> |
這個頭部定義內容:
| 1 | '<root><head><title>Well Dola!</title></head><body>I love Dola!</body></root>' |
怎么辦呢?
有一個辦法是使用 minidom 來實現,方法如下:
| 1 2 3 4 5 | from xml.dom import minidom # 使用 minidom 解析 tree = minidom.parseString(xml_string) # 重新生成 xml 字符串 xml_string = tree.toxml() |
雖然讓計算機多運行了一些代碼,但是這樣可以把問題解決掉。
最后生成的 xml 代碼如下:
| 1 | u'<?xml version="1.0" ?><root><head><title>Well Dola!</title></head><body>I love Dola!</body></root>' |
當然還可以使用 minidom 中 tree 對象的 toprettyxml 方法把 xml 打得漂亮一點。
總結
以上是生活随笔為你收集整理的使用 Python ElementTree 生成 xml的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ set的一些用法
- 下一篇: python numpy.random