はいそれでは表題の件やっていきます。
今回はDOMを使ってXMLを生成し、ファイルに書き込んでいきます。
(DOMについては前の記事やwikiで調べてください。)
サンプルはC++ GUI Programming with Qt4 348ページのものをやや変更して使用します。
そして、いつものようにQtCreaterの使用を前提とします。(QtCreaterなどの使い方は ”Qtをはじめよう" を見てください。)
なお、.proファイルに Qt += xml の記述をしておいてください。でなければQXml関連をコードに含められません。
ではコードを
(mainwindow.cpp)
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QFile file("C:\\Users\\windows7\\Desktop\\test.txt");
if (file.open(QFile::WriteOnly| QFile::Truncate))
{
const int Indent = 4;
QDomDocument doc;
QDomElement root = doc.createElement("doc");
QDomElement quote = doc.createElement("quote");
QDomElement translation = doc.createElement("sample");
QDomText latin = doc.createTextNode("Writting XML Sample");
QDomText english = doc.createTextNode("Hello Sample XML !!");
doc.appendChild(root);
root.appendChild(quote);
root.appendChild(translation);
quote.appendChild(latin);
translation.appendChild(english);
QTextStream out(&file);
doc.save(out, Indent);//第2引数はインデントのスペース数
}
}
はい簡単ですね。
まずcreateElementで要素をそれぞれ作成しています。次に内容にセットするためのテキストをcreateTextNodeで作成し、それぞれツリーにappendChildでセットしていきます。最後にsaveでファイルに書き出しています。
(QDomDocumentリファレンス)
書き出したファイルの内容は以下のようになります。
<doc>
<quote>Writting XML Sample</quote>
<sample>Hello Sample XML !!</sample>
</doc>
以上です。
※補足:他のエンコーディングを使うようにXMLファイル先頭で宣言するには、下記のように書けばいいようです。
QTextStream out(&file);
QDomNode xmlNode = doc.createProcessingInstruction("xml",
"version=\"1.0\" encoding=\"ISO-8859-1\"");
doc.insertBefore(xmlNode, doc.firstChild());
doc.save(out, Indent);
