xml模块
Posted 与君同悦
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xml模块相关的知识,希望对你有一定的参考价值。
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模块的主要内容,如果未能解决你的问题,请参考以下文章
xml Eclipse模板(代码片段)检查参数并最终抛出IllegalArgumentException
从 XML 声明片段获取 XML 编码:部分内容解析不支持 XmlDeclaration