參考文章:https://blog.csdn.net/weixin_42749767/article/details/82770563
先介紹xml.dom.minidom包,有一個讀寫的例子
read_write_xml.py

from xml.dom.minidom import parse import xml.dom.minidom import os def is_xml_exist(xml_path): xml_exist = os.path.exists(xml_path) if not xml_exist: return False return True """ movie.xml <collection shelf="New Arrivals"> <movie title="Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title="Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title="Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection> """ def read_movie_xml(): path = "movie.xml" if not is_xml_exist(path): print("%s is not exist" % path) else: # 使用minidom解析器打開XML文檔 open_xml = parse(path) root_node = open_xml.documentElement shelf_attrib = "shelf" if root_node.hasAttribute(shelf_attrib): print("Lable: %s\tAttrib: %s\t\tValue: %s" % ( root_node.nodeName, shelf_attrib, root_node.getAttribute(shelf_attrib))) print("") # 在集合中獲取所有電影 movie_node = "movie" movies = root_node.getElementsByTagName(movie_node) # 打印每部電影的詳細信息 for movie in movies: print("**** Movie ****") if movie.hasAttribute("title"): print("Title: %s" % movie.getAttribute("title")) type_movie = movie.getElementsByTagName('type')[0] print("Type: %s" % type_movie.childNodes[0].data) format_movie = movie.getElementsByTagName('format')[0] print("Format: %s" % format_movie.childNodes[0].data) rating_movie = movie.getElementsByTagName('rating')[0] print("Rating: %s" % rating_movie.childNodes[0].data) descrip_movie = movie.getElementsByTagName('description')[0] print("Rating: %s" % descrip_movie.childNodes[0].data) print("") if __name__ == "__main__": read_movie_xml()
運行結果:
用到的知識點:
1. 導入xml包:
from xml.dom.minidom import parse
2. 打開xml文件:
open_xml = parse(path)
root_node = open_xml.documentElement
3. 獲取節點名稱:
root_node.nodeName
4. 判斷節點屬性是否存在:
root_node.hasAttribute(shelf_attrib)
5. 獲取節點屬性:
root_node.getAttribute(shelf_attrib)
6. 獲取子節點對象:
root_node.getElementsByTagName(movie_node)
7. 獲取文本節點的文本信息:
type_movie.childNodes[0].data
以上語句務必正確使用,運行第二步,xml必須已經存在,運行第六步,子節點的標簽必須存在,運行第七步,此節點必須是文本節點,否則都會出現異常。