def __init__(self): super(MainWindow, self).__init__(None) uic.loadUi("./mainwindow.ui", self) doc = QDomDocument() # 添加处理指令即XML说明 instruction = QDomProcessingInstruction() instruction = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"") doc.appendChild(instruction) # 添加根元素 root = doc.createElement(QString("书库")) doc.appendChild(root) # 添加根元素 # 添加第一个图书元素及其子元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() id.setValue(QString("1")) book.setAttributeNode(id) text = doc.createTextNode(QString("Qt")) title.appendChild(text) text = doc.createTextNode(QString("shiming")) author.appendChild(text) book.appendChild(title) # 图书元素 添加 书名元素 book.appendChild(author) # 图书元素 添加 作者元素 root.appendChild(book) # 根元素 添加 图书元素 # 添加第二个图书元素及其子元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) id.setValue(QString("2")) book.setAttributeNode(id) text = doc.createTextNode(QString("Linux")) title.appendChild(text) text = doc.createTextNode(QString("yafei")) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) file = QFile("my.xml") if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("open my.xml Err") out = QTextStream(file) doc.save(out, 4) # 将文档保存到文件,4为子元素缩进字符数 file.close()
def on_pushButton_4_clicked(self): # 我们先清空显示,然后显示“无法添加!”,这样如果添加失败则会显示“无法添加!” self.listWidget.clear() self.listWidget.addItem(QString("无法添加!")) file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open my.xml Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if not status: file.close() raise Exception(str(rrorMsg)) file.close() root = doc.documentElement() # 获取根元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() # 我们获得了最后一个孩子结点的编号,然后加1,便是新的编号 num = root.lastChild().toElement().attribute(QString("编号")) count = num.toInt() + 1 id.setValue(QString.number(count)) book.setAttributeNode(id) text = doc.createTextNode(self.lineEdit_2.text()) title.appendChild(text) text = doc.createTextNode(self.lineEdit_3.text()) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("file open Err") out = QTextStream(file) doc.save(out, 4) file.close() # 最后更改显示为“添加成功!” self.listWidget.clear() self.listWidget.addItem(QString("添加成功!"))