一. xml相关术语:

1.Document(文档): 对应一个xml文件

2.Declaration(声明):

<?xml version="1.0" encoding="utf-8"?>

version指定了版本,encoding指定了文件编码

3.Comment(注释),同html中的注释

<!--just a comment about book_store-->

4.Element(元素):指的是从( 且包括) 开始标签直到
( 且包括) 结束标签的部分,如<book_store></book_store>

<book_store name="newhua" website="https://www.amazon.cn/b?node=1876097071">
<book1>
<name>hamlet</name>
<author>William Shakespeare</author>
</book1>
</book_store>

5.Tag(标签): 用于表示素的起始与结束,如book1,name,author等

6.Attribute(属性),如上面的name,website

7.Text(文本),如hamelt

二.解析xml

有三种方法

from xml.dom.minidom import parse,parseString

dom1 = parse('test.xml')  #通过文件名解析xml
data = open('test.xml')
dom2 = parse(data) #通过解析已打开的xml文件 note = """
<note>
<to>Peter</to>
<from>Jane</from>
<heading>Reminder</heading>
<body>Don't be late for the meeting</body>
</note>
"""
dom3 = parseString(note) #解析字符串

2.得到根元素

doc = parse('test.xml')  #通过文件名解析xml
root = doc.documentElement

三.创建xml

from xml.dom.minidom import Document
doc = Document() #创建一篇空的文档 from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
#创建doc,并且添加根节点book_store
doc = impl.createDocument(None,"book_store",None)
print(doc.documentElement.tagName) #book_store #doc同doc=Document()
doc2 = impl.createDocument(None,None,None)

四.类及层次结构

可以发现:Element,Text,Comment,Attribute的创建工作全部由Document完成,然后通过appendChild或insertBefore方法将新的对象插入到Document中。

五.具体操作

1.解析xml文件

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

代码:

import xml.dom.minidom
from xml.dom.minidom import parse #使用minidom解析器打开xml文档
tree = xml.dom.minidom.parse('movies.xml')
#print(type(tree)) #<class 'xml.dom.minidom.Document'>
collection = tree.documentElement #获取文档根元素
if collection.hasAttribute('shelf'):
print("root element attribute:",collection.getAttribute("shelf"))
#print(collection.getAttribute('shelf')) #获取属性
movie_list = collection.getElementsByTagName('movie')
movie_info_list = []
for movie in movie_list:
print('******Movie*****')
if movie.hasAttribute("title"):
title = movie.getAttribute('title')
print('Title',title)
type = movie.getElementsByTagName('type')[0].childNodes[0].data
format = movie.getElementsByTagName('format')[0].childNodes[0].data
rating = movie.getElementsByTagName("rating")[0].firstChild.data
stars = movie.getElementsByTagName('stars')[0].firstChild.data
description = movie.getElementsByTagName("description")[0].firstChild.data
print("type: ", type)
print("format: ", format)
print("rating: ", rating)
print("stars: ", stars)
print('description: ', description)

2.写xml文件

效果:

<?xml version="1.0" encoding="utf-8"?>
<!--just a comment about book_store-->
<book_store name="amzon" website="https://www.amazon.cn/b?node=1876097071">
<book1>
<name>hamlet</name>
<author>William Shakespeare</author>
</book1>
</book_store>

代码:

from xml.dom.minidom import Document
doc = Document()

 comment = doc.createComment('just a comment about book_store') #添加注释
  doc.appendChild(comment)

# from xml.dom.minidom import getDOMImplementation
# impl = getDOMImplementation()
# doc = impl.createDocument(None, None, None) book_store = doc.createElement('book_store') # 创建根节点
book_store.setAttribute('name', 'amazon') #设置属性
book_store.setAttribute('website', 'https://www.amazon.cn/b?node=1876097071')
doc.appendChild(book_store) #添加节点
book1 = doc.createElement('book1') #创建元素book1
book1_name = doc.createElement('name')
book1_name_value = doc.createTextNode('hamlet') #创建text节点
book1_name.appendChild(book1_name_value)
book1_author = doc.createElement('author')
book1_author_value = doc.createTextNode('William Shakespeare')
book1_author.appendChild(book1_author_value)
book1.appendChild(book1_name)
book1.appendChild(book1_author)
book_store.appendChild(book1) print(doc.toprettyxml(indent='\t', newl='\n', encoding='utf-8').decode('utf-8'))
# with open('book_store.xml','wb') as f: #写入的数据是bytes类型,所以wb方法写入
# data = doc.toprettyxml(indent='\t', newl='\n', encoding='utf-8') #bytes类型数据
# f.write(data)
with open('test_store.xml', 'w') as f:
doc.writexml(f, indent='\t', newl='\n', encoding='utf-8') #写入的是str类型数据,所以w方法写入

3.简单封装

class MyXMLGenerator:
def __init__(self,xml_name):
self.xml_name = xml_name
self.doc = xml.dom.minidom.Document() def createComment(self,value):
c = self.doc.createComment(value)
self.doc.appendChild(c) def setNodeAttribute(self,node,attname,value):
node.setAttribute(attname,value) def createElement(self,tagName):
ele = self.doc.createElement(tagName)
return ele def appendChild(self,node,parent_node=None):
if parent_node is not None:
parent_node.appendChild(node)
else:
self.doc.appendChild(node) def setNodeValue(self,node,value):
text_node = self.doc.createTextNode(value)
node.appendChild(text_node) def genXML(self):
#print(self.doc.toprettyxml(indent='\t',newl='\n',encoding='utf-8').decode('utf-8'))
with open(self.xml_name,'wb') as f:
data = self.doc.toprettyxml(indent='\t',newl='\n',encoding='utf-8') #python3中二进制数据
f.write(data)

参考:

https://docs.python.org/3/library/xml.dom.minidom.html

https://docs.python.org/3/library/xml.dom.html

xml dom minidom的更多相关文章

  1. python 应用xml.dom.minidom读xml

    xml文件 <?xml version="1.0" encoding="utf-8"?> <city> <name>上海&l ...

  2. python模块:xml.dom.minidom

    """Simple implementation of the Level 1 DOM. Namespaces and other minor Level 2 featu ...

  3. python XML文件解析:用xml.dom.minidom来解析xml文件

    python解析XML常见的有三种方法: 一是xml.dom.*模块,是W3C DOM API的实现,若需要处理DOM API则该模块很合适, 二是xml.sax.*模块,它是SAX API的实现,这 ...

  4. python 之模块之 xml.dom.minidom解析xml

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python 之模块之 xml.dom.minidom解析xml #http://www.cnblogs.c ...

  5. Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件,封装函数

    总结了一下使用Python对xml文件的解析,用到的模块儿如下: 分别从xml字符串和xml文件转换为xml对象,然后解析xml内容,查询指定信息字段. from xml.dom.minidom im ...

  6. python xml.dom模块解析xml

    1. 什么是xml?有何特征? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 例子:del.xml <?xml version=&q ...

  7. Python使用xml.dom解析xml

    在菜鸟教程上找了个关于电影信息的xml类型的文档,用python内置的xml.dom来解析提取一下信息. 先复习一下xml概念: XML 指可扩展标记语言(EXtensible Markup Lang ...

  8. python 解析XML python模块xml.dom解析xml实例代码

    分享下python中使用模块xml.dom解析xml文件的实例代码,学习下python解析xml文件的方法. 原文转自:http://www.jbxue.com/article/16587.html ...

  9. htm Dom对象与 Xml Dom对象的理解

    html 是基于Xml的文档规范.是一种特殊的xml文档,这一点很重要 1.xml 文档的操作,java,c#,...各种语言都提供了很好的api对文档进行解析,操作.当然js 也不例外,提供了一系列 ...

随机推荐

  1. 使用MyEclipse将HTML5移动项目迁移到PhoneGap(一)

    MyEclipse开年钜惠 在线购买低至75折!立即开抢>> [MyEclipse最新版下载] 一.创建一个新的PhoneGap应用程序项目 PhoneGap应用程序项目的结构与HTML5 ...

  2. CUDA ---- Branch Divergence and Unrolling Loop

    Avoiding Branch Divergence 有时,控制流依赖于thread索引.同一个warp中,一个条件分支可能导致很差的性能.通过重新组织数据获取模式可以减少或避免warp diverg ...

  3. 爱宝A-1180热转印条码打印机 打印乱码,对不齐的问题

    本文记录了在使用打印机打印时出现的问题 上线对齐... 1拆开后看了.机械.没有问题. 2考虑打印设置.. 发现问题不大 3询问官网. 重新安装驱动 重新换纸张. ·条码机_win xp.7.8.10 ...

  4. rem 移动端适配

    1.从网易与淘宝的font-size思考前端设计稿与工作流 http://www.cnblogs.com/lyzg/p/4877277.html 2.淘宝弹性布局方案lib-flexible实践 ht ...

  5. tp 缓存,前台提速

  6. Ubuntu使用Remastersys封装制作系统ISO镜像

    首先下载Remastersys的Deb软件包 链接:http://pan.baidu.com/s/1i3tYPKT 密码:qvyd 使用命令强制安装 dpkg --force-all -i remas ...

  7. 如何学php少走弯路

    我是自学php,而且是非计算机专业,算半路出家的.(工作了一段时间又自学编程) 1.一本好书至关重要.如果这本书的知识非常深入,那么还是不要看了.对初学者来说只能是打击.因为很多东西都看不懂.一本知识 ...

  8. liunx系统和其它的基本命令

    1.su   更换用户 2.sudo   管理员权限 3.PATH 4.sudo shutdown -h now   现在关机 sudo shutdown -r now   现在重启 5.kill   ...

  9. OVSSL企业证书认证

    最近,在做http->https的转化,虽然我没有操作证书的安装过程,但是在这个过程中学习到不少知识呢. 因为我没有操作,所以操作上我就不知道了.下面是这个过程中要注意的一些事项: 1.公司名称 ...

  10. 【java编程】重写HashCode和equals方法

    [一]重写equals方案的规则 equals方法本来的原则 1.类的每个实例本质上都是唯一的. 2.不关心类是否提供了“逻辑相等”的测试功能 3.超类已经覆盖了equals,从超类继承过来的行为对于 ...