XML的操作有两种方法,即DOM方式和SAX方式。二者主要区别是:DOM实现方式操作非常简单,但不适合处理过大文件;而SAX实现方式是能处理很大的XML文件,但是需要开发者写一些复杂的代码。Qt提供了对应于这两种用于读取、操作和编写XML的实现类,分别是QDomDocument类和QXmlStreamReader类。
XML格式常用于文件配置,而JSON格式常用于数据传输;XML因为格式规定的限制,会产生较多冗余信息!
XML格式(如下图):
一个XML文件有且只有一个根节点;
XML文档内每一个开始标签都必须对应一个结束标签,
XML的标签内的属性严格区分大小写,也就是<books>和<Books>是两个不同的标签
XML标签的属性值必须用“""”包含起来,如<?xml version="1.0" encoding="UTF-8"?>(分别表示版本号,和字符编码规范)
创建节点的主要操作有:
QDomDocument doc;
1).创建根节点:QDomElement root = doc.createElement("root")
2).创建元素节点:QDomElement element = doc.createElement("nodeName");
3).添加元素节点到根节点:root. appendChild(element);
4).创建元素文本:QDomText nodeText=doc.createTextNode("text");
5).添加元素文本到元素节点:element. appendChild(nodeText);
例子:
头文件定义:
QDomDocument doc;
QStringList PlaySongName;
QString historyName;
QStringList pathList;
QString fileName = "Song.xml";
//写XML
void WriteXml(QStringList &MusicPaths);
//读XML
void readXml(QString& fileName, QDomDocument &XmlDoc);
void addXml(const QString & name,
const QString & text,
QDomDocument &document);
void AnalysisListData(QDomDocument &xmldoc,QFile &File);
QString DeleteFileNameSpecialCharacters(QString &songName);
函数的实现:
void WriteXml(QStringList &MusicPaths);
void MainWindow::WriteXml(QStringList &MusicPaths)
{
doc.clear();
if (doc.toString().compare("")==0){
//创建根节点
QDomElement root = doc.createElement("Song");
//添加根节点
doc.appendChild(root);
}
// QStringList::iterator iter;
int k = 0,i = 0;
for(i = 0;i < MusicPaths.size();++i)
{
//分离出多个MP3文件路径中每个文件的所有信息
QString musicPath = MusicPaths.at(k++);
//从MP3文件信息中获取文件名及文件格式信息
QString FileName = QFileInfo( musicPath ).fileName();
QString songName = DeleteFileNameSpecialCharacters(FileName);
addXml(songName,musicPath,doc);
//qDebug()<<"i="<<i<<" size="<<MusicPaths.size();
}
// fileName = "Song.xml";
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly| QIODevice::Text))
return ;
//将文本流保存到文件,4为子元素缩进的字符数
QTextStream out(&file);
doc.save(out, 4, QDomNode::EncodingFromTextStream);
file.close();
readXml(fileName,doc);
}
void readXml(QString& fileName, QDomDocument &XmlDoc);
void MainWindow::readXml(QString &fileName,
QDomDocument &XmlDoc)
{
QFile file(fileName);
qDebug()<<fileName<<" readonly history list";
if (!file.open(QIODevice::ReadOnly)){
// qDebug()<<file.errorString();
// qDebug()<<file.error();
// qDebug()<<"open file failed";
return ;
}
AnalysisListData(XmlDoc,file);
QDomElement root = XmlDoc.documentElement();//读取根节点
//读取第一个子节点
QDomNode node = root.firstChild();
//遍历节点
QDomNodeList list = root.childNodes();
int count = list.count();
qDebug() << "node count:" << count;
int i = 0;
while (i < count)
{
//获取节点的内容
QString data = node.toElement().text();
// qDebug () << "read == "<<data;
m_playList->addMedia(QUrl::fromLocalFile(data));
// PlaySongName.push_back(QFileInfo( data ).fileName());
historyName = data.split("/").last();
ui->MusicWidget->addItem(historyName);
//读取下一个兄弟节点
node = node.nextSibling();
node.nextSiblingElement();
i++;
}
file.close();
}
void addXml(const QString & name, const QString & text, QDomDocument &document);
void MainWindow::addXml(const QString &name,
const QString &text,
QDomDocument &document)
{
//读取根节点
QDomElement root = document.documentElement();
//创建元素节点
QDomElement newChild = document.createElement(name);
//添加元素节点到根节点
root.appendChild(newChild);
//创建元素文本
QDomText newChildText = document.createTextNode(text);
//添加元素文本到元素节点
newChild.appendChild(newChildText);
}
void MainWindow::AnalysisListData(QDomDocument &xmldoc, QFile &File)
void MainWindow::AnalysisListData(QDomDocument &xmldoc, QFile &File)
{
QString errorStr;
int errorLine = 0,errorCol = 0;
if(!xmldoc.setContent(&File,true,&errorStr,&errorLine,&errorCol))
{
//如果出错,则会进入这里。errorStr得到的是出错说明,errorLine和errorCol则是出错的行和列
qDebug() << errorStr << "line: " << errorLine << "col: " << errorCol;
return;
}
}
QString MainWindow::DeleteFileNameSpecialCharacters(QString &songName)
QString MainWindow::DeleteFileNameSpecialCharacters(QString &songName)
{
//处理特殊字符等(可自定义)
songName = songName.replace(' ',"").replace(':',"");
songName = songName.replace('-',"").replace('(',"");
songName = songName.replace(')',"").replace('.',"");
return songName;
}