码迷,mamicode.com
首页 > 其他好文 > 详细

xml模块

时间:2018-04-17 11:50:00      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:信息   nod   dev   错误信息   tno   ruby   des   操作   orm   

xml.etree.ElementTree模块操作xml

import xml.etree.ElementTree as ET

tree = ET.parse("books.xml")
root = tree.getroot()
print(type(root))
print(root.tag)   #booklist

#遍历所有节点
for i in root:
	print(i.tag,i.attrib)
	for child in i:
		print("\t", child.tag,child.text)

#遍历指定节点
for i in root.iter(‘name‘):
	print(i.tag, i.text)

#增加节点
book = ET.Element(‘book‘, {‘id‘: ‘5‘})
name = ET.SubElement(book, ‘name‘)
name.text = ‘Shell‘
author = ET.SubElement(book, ‘author‘)
author.text = ‘laocao‘
root.append(book)


#删除节点
books = root.findall(‘book‘)
for book in books:
    name = book.find(‘name‘)
    if name.text == "Shell":
        book.remove(name)
    else:
        pass

#更改节点
books = root.findall(‘book‘)
for book in books:
    name = book.find(‘name‘)
    if name.text == "Shell":
        name.text = "Ruby"
    else:
        pass

tree.write(‘books.xml‘, encoding="UTF-8", xml_declaration=True)

  minidom模块操作xml

from xml.dom import minidom

dom = minidom.parse("books.xml")
root = dom.documentElement
print(root.nodeName)
print(root.nodeType)
print(root.childNodes)
name = root.getElementsByTagName(‘name‘)
for i in name:
    print(i.childNodes[0].nodeValue)

#新增节点
book = dom.createElement(‘book‘)
book.setAttribute(‘id‘,‘6‘)
name = dom.createElement(‘name‘)
name_text = dom.createTextNode("Perl")
name.appendChild(name_text)
author = dom.createElement(‘author‘)
author_text = dom.createTextNode("laoda")
author.appendChild(author_text)
book.appendChild(name)
book.appendChild(author)
root.appendChild(book)
try:
    with open("books.xml", ‘w‘, encoding="UTF-8") as f:
        dom.writexml(f, encoding="UTF-8")
        print("写入xml成功!")
except Exception as err:
    print("错误信息:{0}".format(err))

  

xml模块

标签:信息   nod   dev   错误信息   tno   ruby   des   操作   orm   

原文地址:https://www.cnblogs.com/ericbai/p/8861798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!