-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweighttablemodelio.cpp
More file actions
93 lines (77 loc) · 2.35 KB
/
weighttablemodelio.cpp
File metadata and controls
93 lines (77 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <QXmlStreamReader>
#include <QDate>
#include <QLocale>
#include "weightdatamanager.h"
#include "weighttablemodelio.h"
#include "weighttablemodel.h"
namespace weighttracker {
bool WeightTableModelIO::populateModelFromFile(WeightTableModel& model, const QString &fileName)
{
XMLReader reader(fileName);
DataVector data;
bool result = reader.read(data);
model.setWeightData(std::move(data));
return result;
}
bool WeightTableModelIO::writeModelToFile(WeightTableModel& model, const QString &fileName)
{
XMLWriter writer(fileName);
return writer.write(model.getWeightData());
}
XMLReader::XMLReader(QString filename) : file_(filename)
{ }
bool XMLReader::read(DataVector &data)
{
bool open = file_.open(QIODevice::ReadOnly | QIODevice::Text);
if (!open)
return false;
else
{
data.clear();
QXmlStreamReader xml(&file_);
while (!xml.atEnd())
{
xml.readNext();
if(xml.name() == "weight")
{
QString dateString = xml.attributes().value("date").trimmed().toString();
QDate date = QDate::fromString(dateString, QLocale().dateFormat(QLocale::ShortFormat));
bool correctDouble = true;
double value = xml.readElementText().toDouble(&correctDouble);
if (date.isValid() && correctDouble)
data.emplace_back(DataPoint(date, value));
else
return false;
}
}
file_.close();
return true;
}
}
XMLWriter::XMLWriter(QString filename) : file_(filename)
{ }
bool XMLWriter::write(const DataVector &data)
{
bool open = file_.open(QIODevice::WriteOnly | QIODevice::Text);
if (!open)
return false;
else
{
QXmlStreamWriter xml(&file_);
xml.setAutoFormatting(true);
xml.writeStartDocument();
xml.writeStartElement("weight_points");
for (auto& el : data)
{
xml.writeStartElement("weight");
xml.writeAttribute("date", QLocale().toString(el.date, QLocale::ShortFormat));
xml.writeCharacters(QString::number(el.value,'f', 1));
xml.writeEndElement();
}
xml.writeEndElement(); // weights
xml.writeEndDocument();
file_.close();
return !xml.hasError();
}
}
}