在使用QDomDocument读写xml之前需要在工程文件添加:
QT += xml
1.生成xml文件
void createXml(QString xmlName)
{QFile file(xmlName);if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate |QIODevice::Text))return false;QDomDocument doc;QDomProcessingInstruction instruction; //添加处理命令instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");doc.appendChild(instruction);
/*
<bookstore><book category="c++"><price>98</price></book><book category="语文"><price>100</price></book>
</bookstore>
*/QDomElement root = doc.createElement("bookstore");doc.appendChild(root);QDomElement book = doc.createElement("book");book.setAttribute("category", "C++"); //生成category节点root.appendChild(book);QDomElement price= doc.createElement("price");book.appendChild(price);QDomText text = doc.createTextNode("98");price.appendChild(text);book = doc.createElement("book");book.setAttribute("category", QString::fromLocal8Bit("语文"));root.appendChild(book);price= doc.createElement("price");book.appendChild(price);text = doc.createTextNode("100");price.appendChild(text);QTextStream stream(&file);stream.setCodec("UTF_8");doc.save(stream,4,QDomNode::EncodingFromTextStream);file.close();
}
2.读取xml文件
void loadXml(QString xmlName)
{QFile file(xmlName);if(!file.open(QFile::ReadOnly | QFile::Text)){return;}QString strError;int errorLine;int errorColumn;QDomDocument doc;if(!doc.setContent(&file, false, &strError, &errorLine, &errorColumn)){return;}QDomElement root = doc.documentElement();if(root.tagName() == "bookstore"){QDomNode book = root.firstChild();while(!book.isNull()){if(book.toElement().tagName() == "book"){QString str = book.toElement().attribute("category"); //获取category属性内容qDebug()<<str;QDomNode node = book.firstChild();while(!node.isNull()){if(node.toElement().tagName() == "price"){QString price = node.toElement().text();qDebug()<<price;}node = node.nextSibling();}}book = book.nextSibling();}}
}
void appendXml(QDomDocument &doc,QDomElement &root)
{QDomElement book = doc.createElement("book");book.setAttribute("category", "C++"); //生成category节点root.appendChild(book);QDomElement price= doc.createElement("price");book.appendChild(price);QDomText text = doc.createTextNode("98");price.appendChild(text);book = doc.createElement("book");book.setAttribute("category", QString::fromLocal8Bit("语文"));root.appendChild(book);price= doc.createElement("price");text = doc.createTextNode("100");price.appendChild(text);book.appendChild(price);
}
void openFileWriteXML(QString xmlPath)
{QFile file(xmlPath);if(!file.open(QFile::ReadOnly | QFile::Text)){return;}QString strError;int errorLine;int errorColumn;QDomDocument doc;if(!doc.setContent(&file, false, &strError, &errorLine, &errorColumn)){return;}QDomElement root = doc.documentElement();}