Python使用minidom读写xml的方法

  • Post category:Python

下面就为您详细讲解“Python使用minidom读写xml的方法”的完整攻略。

什么是XML

XML(可扩展标记语言,eXtensible Markup Language),是一种标记式语言,被用来存储和传输数据。XML的语法与HTML类似,但是XML并不是为显示数据而设计的,而是为了传输数据而设计的。

XML有一个重要的特点就是可扩展性,这意味着我们可以定义自己的标记来适应各种不同的数据格式。

Python中的XML解析

Python中支持多种XML解析库,其中minidom是Python自带的一个库。

安装

pip install minidom     

读取XML文件

读取XML文件,需要先解析XML文档,再通过DOM树的节点类型和关系来访问或修改XML文件的内容。下面是一个读取”books.xml”文件的示例:

# -*- coding: utf-8 -*-
from xml.dom.minidom import parse
import xml.dom.minidom

dom_tree = xml.dom.minidom.parse('books.xml')
collection = dom_tree.documentElement
if collection.hasAttribute("shelf"):
   print ("Root element : %s" % collection.getAttribute("shelf"))

books = collection.getElementsByTagName("book")

for book in books:
   if book.hasAttribute("category"):
      print ("Category: %s" % book.getAttribute("category"))

   title = book.getElementsByTagName('title')[0]
   author = book.getElementsByTagName('author')[0]
   year = book.getElementsByTagName('year')[0]
   price = book.getElementsByTagName('price')[0]
   print ("Title: %s, Author: %s, Year: %s, Price: %s" % (
          title.childNodes[0].data, author.childNodes[0].data,
          year.childNodes[0].data, price.childNodes[0].data))

创建XML

可以使用DOM创建XML元素,首先创建Document对象,然后创建各种节点,最后将节点归属到XML中。下面是一个创建”books.xml”文件的示例:

# -*- coding: utf-8 -*-
from xml.dom.minidom import Document

doc = Document()

root = doc.createElement('books')
root.setAttribute('shelf', 'New Arrivals')
doc.appendChild(root)

book1 = doc.createElement('book')
book1.setAttribute('category', 'cooking')
root.appendChild(book1)

title1 = doc.createElement('title')
title1.appendChild(doc.createTextNode('Everyday Italian'))
book1.appendChild(title1)
author1 = doc.createElement('author')
author1.appendChild(doc.createTextNode('Giada De Laurentiis'))
book1.appendChild(author1)
year1 = doc.createElement('year')
year1.appendChild(doc.createTextNode('2005'))
book1.appendChild(year1)
price1 = doc.createElement('price')
price1.appendChild(doc.createTextNode('30.00'))
book1.appendChild(price1)

f = open('books.xml', 'w')
f.write(doc.toprettyxml(indent='\t'))
f.close()

总结

以上就是Python中使用minidom读写XML的方法,通过它能够快速处理和生成XML文件。