http://blog.csdn.net/xiexingshishu/article/details/45177023
1、DOM方式
- QFilefile("d:/test.txt");
- file.open(QIODevice::WriteOnly);
- QDomDocumentdoc;
- QDomProcessingInstructioninstruction;
- instruction=doc.createProcessingInstruction("xml","version=\'1.0\'");
- doc.appendChild(instruction);
- QDomElementroot=doc.createElement("html");
- doc.appendChild(root);
- QDomElementdata;
- QDomElementtmp;
- QDomTexttext;
- data=doc.createElement("title");
- text=doc.createTextNode(QStringLiteral("多看"));
- data.appendChild(text);
- root.appendChild(data);
- tmp=doc.createElement("book");
- "小说"));
- tmp.appendChild(text);
- root.appendChild(tmp);
- QTextStreamout(&file);
- doc.save(out,4);
- file.close();
读代码为
file.open(QIODevice::ReadOnly);
QDomDocumentdoc;
doc.setContent(&file);
QDomElementroot=doc.documentElement();
for(QDomNodenode=root.firstChild();!node.isNull();node=node.nextSibling()){
QDomElementelement=node.toElement();
QStringtagName=element.tagName();
if(tagName=="title"){
qDebug()<<element.text();
}else"book"){
}
}
2、用QXmlStreamReader和QXmlStreamWriter
QXmlStreamWriterxmlstreamwriter(&file);
xmlstreamwriter.setAutoFormatting(true);
xmlstreamwriter.writeStartDocument();
xmlstreamwriter.writeStartElement("xml");
"round");
xmlstreamwriter.writeAttribute("id",mRoundId);
"tableid",mTableId);
//player1
"player1");
"framescore",mPlayer1Frame);
"points",mPlayer1Point);
"break",mPlayer1ContinuePoint);
xmlstreamwriter.writeCharacters("HelloWorld");//添加内容
xmlstreamwriter.writeEndElement();
//player2
"player2");
xmlstreamwriter.writeEndElement();
xmlstreamwriter.writeEndDocument();file.close();
结果如下:
以QDomAttr方式写:
QDomAttrdata;
QDomAttrtmp;
data=doc.createAttribute("title");
data.setValue(QStringLiteral("多看"));
root.setAttributeNode(data);
tmp=doc.createAttribute(tmp.setValue(QStringLiteral(root.setAttributeNode(tmp);
QTextStreamout(&file);
读QDomAttr
file.close();
qDebug()<<root.attribute("book");
2、用QXmlStreamReader和QXmlStreamWriter
写文件,设置相关联的文件,用writeStartDocument来开始,用writeEndDocument来结束
用writeStartElement和writeEndElement来表示元素的开始和结束,需要成对使用
<name>a</name>形式,用writeTextElement
<name a=""/>形式,用writeAttribute
"test.txt");file.open(QIODevice::writeOnly);
<?xmlversion="1.0"encoding="UTF-8"?>
读文件时,用isStartElement来判断标志的起始
<name a=""></name>形式,用attributes().value("a")
<name>a</name>形式,用readElementText
在读取时,是通过循环,while (!reader.atEnd()) {reader.readNext();.....;}
"test.txt");