/
Document.cpp
259 lines (201 loc) · 5.92 KB
/
Document.cpp
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#include "Document.h"
#include "XPathException.h"
#include "itextstream.h"
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <vector>
namespace xml
{
// Construct a wrapper around the provided xmlDocPtr.
Document::Document(xmlDocPtr doc):
_xmlDoc(doc)
{}
Document::Document(const std::string& filename) :
_xmlDoc(xmlParseFile(filename.c_str()))
{}
Document::Document(std::istream& stream) :
_xmlDoc(nullptr)
{
const std::size_t bufferSize = 4096;
static_assert(bufferSize < std::numeric_limits<std::size_t>::max());
std::vector<char> buffer(bufferSize);
// Read 1 byte to construct the parser context
stream.read(buffer.data(), 1);
if (stream.gcount() != 1)
{
rError() << "[xml::Document] Could not read a single byte from the given stream." << std::endl;
return;
}
auto ctxt = xmlCreatePushParserCtxt(nullptr, nullptr, buffer.data(), 1, "stream");
while (!stream.eof())
{
stream.read(buffer.data(), buffer.size());
auto error = xmlParseChunk(ctxt, buffer.data(), static_cast<int>(stream.gcount()), 0);
if (error != 0)
{
xmlFreeParserCtxt(ctxt);
return;
}
}
// Terminate the parser
auto error = xmlParseChunk(ctxt, buffer.data(), 0, 1);
if (error != 0)
{
xmlFreeParserCtxt(ctxt);
return;
}
_xmlDoc = ctxt->myDoc;
xmlFreeParserCtxt(ctxt);
}
Document::~Document()
{
if (_xmlDoc != nullptr)
{
// Free the xml document memory
xmlFreeDoc(_xmlDoc);
}
}
Document Document::create()
{
xmlChar* versionStr = xmlCharStrdup("1.0");
// Create a new xmlDocPtr and return the object
xmlDocPtr doc = xmlNewDoc(versionStr);
xmlFree(versionStr);
return Document(doc);
}
Document Document::clone(const Document& source)
{
if (source._xmlDoc == nullptr)
{
// Nothing to clone, create an empty doc
return Document(nullptr);
}
// Create a deep copy of the other doc
return Document(xmlCopyDoc(source._xmlDoc, 1));
}
Node Document::addTopLevelNode(const std::string& name)
{
std::lock_guard<std::mutex> lock(_lock);
if (!isValid())
{
return xml::Node(nullptr); // is not Valid, place an assertion here?
}
xmlChar* nameStr = xmlCharStrdup(name.c_str());
xmlChar* emptyStr = xmlCharStrdup("");
xmlNodePtr root = xmlNewDocNode(_xmlDoc, NULL, nameStr, emptyStr);
xmlNodePtr oldRoot = xmlDocSetRootElement(_xmlDoc, root);
if (oldRoot != NULL)
{
// Old root element, remove it
xmlUnlinkNode(oldRoot);
xmlFreeNode(oldRoot);
}
xmlFree(nameStr);
xmlFree(emptyStr);
return Node(root);
}
Node Document::getTopLevelNode() const
{
if (!isValid())
{
// Invalid Document, return a NULL node
return Node(NULL);
}
return Node(_xmlDoc->children);
}
void Document::importDocument(Document& other, Node& importNode)
{
std::lock_guard<std::mutex> lock(_lock);
// Locate the top-level node(s) of the other document
xml::NodeList topLevelNodes = other.findXPath("/*");
xmlNodePtr targetNode = importNode.getNodePtr();
if (targetNode->name == NULL)
{
// invalid importnode
return;
}
// greebo: Not all target nodes already have a valid child node, use a modified algorithm
// to handle that situation as suggested by malex984
// Add each of the imported nodes to the target importNode
for (std::size_t i = 0; i < topLevelNodes.size(); ++i)
{
if (targetNode->children == NULL)
{
xmlUnlinkNode(topLevelNodes[i].getNodePtr());
xmlAddChild(targetNode, topLevelNodes[i].getNodePtr());
}
else
{
xmlAddPrevSibling(targetNode->children, topLevelNodes[i].getNodePtr());
}
}
}
void Document::copyNodes(const NodeList& nodeList)
{
std::lock_guard<std::mutex> lock(_lock);
if (!isValid() || _xmlDoc->children == NULL)
{
return; // is not Valid, place an assertion here?
}
// Copy the child nodes one by one
for (std::size_t i = 0; i < nodeList.size(); i++)
{
// Copy the node
xmlNodePtr node = xmlCopyNode(nodeList[i].getNodePtr(), 1);
// Add this node to the top level node of this document
xmlAddChild(xmlDocGetRootElement(_xmlDoc), node);
}
}
bool Document::isValid() const
{
return _xmlDoc != nullptr;
}
// Evaluate an XPath expression and return matching Nodes.
NodeList Document::findXPath(const std::string& path) const
{
std::lock_guard<std::mutex> lock(_lock);
// Set up the XPath context
xmlXPathContextPtr context = xmlXPathNewContext(_xmlDoc);
if (context == NULL) {
rConsoleError() << "ERROR: xml::findPath() failed to create XPath context "
<< "when searching for " << path << std::endl;
throw XPathException("Failed to create XPath context");
}
// Evaluate the expression
const xmlChar* xpath = reinterpret_cast<const xmlChar*>(path.c_str());
xmlXPathObjectPtr result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
if (result == NULL) {
rConsoleError() << "ERROR: xml::findPath() failed to evaluate expression "
<< path << std::endl;
throw XPathException("Failed to evaluate XPath expression");
}
// Construct the return vector. This may be empty if the provided XPath
// expression does not identify any nodes.
NodeList retval;
xmlNodeSetPtr nodeset = result->nodesetval;
if (nodeset != NULL) {
for (int i = 0; i < nodeset->nodeNr; i++) {
retval.push_back(Node(nodeset->nodeTab[i]));
}
}
xmlXPathFreeObject(result);
return retval;
}
// Saves the file to the disk via xmlSaveFormatFile
void Document::saveToFile(const std::string& filename) const
{
std::lock_guard<std::mutex> lock(_lock);
xmlSaveFormatFile(filename.c_str(), _xmlDoc, 1);
}
std::string Document::saveToString() const
{
std::lock_guard<std::mutex> lock(_lock);
xmlBuffer* buffer = xmlBufferCreate();
xmlOutputBuffer* outputBuffer = xmlOutputBufferCreateBuffer(buffer, nullptr);
xmlSaveFormatFileTo(outputBuffer, _xmlDoc, "utf-8", 1);
std::string output(reinterpret_cast<char*>(buffer->content), buffer->use);
xmlBufferFree(buffer);
return output;
}
}