Qt 5.10 Book Examples
main.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // main.cpp
3 // ======================================================================
4 // This file is a part of the book
5 // "Qt 5.10 Professional programming with C++"
6 // http://qt-book.com
7 // ======================================================================
8 // Copyright (c) 2017 by Max Schlee
9 // ======================================================================
10 
11 #include <QtXml>
12 
13 // ----------------------------------------------------------------------
14 QDomElement makeElement( QDomDocument& domDoc,
15  const QString& strName,
16  const QString& strAttr = QString::null,
17  const QString& strText = QString::null
18  )
19 {
20  QDomElement domElement = domDoc.createElement(strName);
21 
22  if (!strAttr.isEmpty()) {
23  QDomAttr domAttr = domDoc.createAttribute("number");
24  domAttr.setValue(strAttr);
25  domElement.setAttributeNode(domAttr);
26  }
27 
28  if (!strText.isEmpty()) {
29  QDomText domText = domDoc.createTextNode(strText);
30  domElement.appendChild(domText);
31  }
32  return domElement;
33 }
34 
35 // ----------------------------------------------------------------------
36 QDomElement contact( QDomDocument& domDoc,
37  const QString& strName,
38  const QString& strPhone,
39  const QString& strEmail
40  )
41 {
42  static int nNumber = 1;
43 
44  QDomElement domElement = makeElement(domDoc,
45  "contact",
46  QString().setNum(nNumber)
47  );
48  domElement.appendChild(makeElement(domDoc, "name", "", strName));
49  domElement.appendChild(makeElement(domDoc, "phone", "", strPhone));
50  domElement.appendChild(makeElement(domDoc, "email", "", strEmail));
51 
52  nNumber++;
53 
54  return domElement;
55 }
56 
57 // ----------------------------------------------------------------------
58 int main()
59 {
60  QDomDocument doc("addressbook");
61  QDomElement domElement = doc.createElement("addressbook");
62  doc.appendChild(domElement);
63 
64  QDomElement contact1 =
65  contact(doc, "Piggy", "+49 631322187", "piggy@mega.de");
66 
67  QDomElement contact2 =
68  contact(doc, "Kermit", "+49 631322181", "kermit@mega.de");
69 
70  QDomElement contact3 =
71  contact(doc, "Gonzo", "+49 631322186", "gonzo@mega.de");
72 
73  domElement.appendChild(contact1);
74  domElement.appendChild(contact2);
75  domElement.appendChild(contact3);
76 
77  QFile file("addressbook.xml");
78  if(file.open(QIODevice::WriteOnly)) {
79  QTextStream(&file) << doc.toString();
80  file.close();
81  }
82  return 0;
83 }
QDomElement makeElement(QDomDocument &domDoc, const QString &strName, const QString &strAttr=QString::null, const QString &strText=QString::null)
Definition: main.cpp:14
int main(int argc, char **argv)
Definition: main.cpp:15
QDomElement contact(QDomDocument &domDoc, const QString &strName, const QString &strPhone, const QString &strEmail)
Definition: main.cpp:36