-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathXMLTools.cpp
519 lines (415 loc) · 14.6 KB
/
XMLTools.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#include "XMLTools.h"
#include <boost/tokenizer.hpp>
/* Note:
Problems with unresolved external: Make sure under project properties that Treat wchar_t as
Built-in Type is set to Yes (C/C++, the language tab).
*/
#include <QtWidgets/QMessageBox>
#include <sstream>
XMLTools::XMLTools() :
m_doc(0),
m_parser(0)
{}
XMLTools::~XMLTools()
{
//
// Delete the parser itself. Must be done prior to calling Terminate, below.
//
if ( m_parser)
m_parser->release();
// And call the termination method
XMLPlatformUtils::Terminate();
}
bool XMLTools::saveToFile(std::string xmlFile)
{
bool errorOccurred = false;
try
{
AbstractDOMParser::ValSchemes valScheme = AbstractDOMParser::Val_Never;
// initialize if not previously done
if ( m_parser == 0 )
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"
<< StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
return false;
}
// Instantiate the DOM parser.
static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
// check if not previously initialized
if ( m_parser == 0)
m_parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
DOMConfiguration *config = m_parser->getDomConfig();
DOMLSSerializer *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
DOMLSOutput *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();
config->setParameter(XMLUni::fgDOMNamespaces, false);
config->setParameter(XMLUni::fgXercesSchema, false);
config->setParameter(XMLUni::fgXercesSchemaFullChecking, false);
config->setParameter(XMLUni::fgDOMValidate, false);
// enable datatype normalization - default is off
config->setParameter(XMLUni::fgDOMDatatypeNormalization, false);
// And create our error handler and install it
DOMCustomErrorHandler errorHandler;
config->setParameter(XMLUni::fgDOMErrorHandler, &errorHandler);
unsigned long duration;
//reset error count first
errorHandler.resetErrors();
try
{
// plug in user's own error handler
DOMConfiguration* serializerConfig=theSerializer->getDomConfig();
XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(xmlFile.c_str());
theOutputDesc->setByteStream(myFormTarget);
theSerializer->write(m_doc, theOutputDesc);
theOutputDesc->release();
theSerializer->release();
}
catch (const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cerr << "\nError writing: '" << xmlFile.c_str() << "'\n"
<< "Exception message is: \n"
<< StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
errorOccurred = true;
}
catch (const DOMException& toCatch)
{
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
XERCES_STD_QUALIFIER cerr << "\nDOM Error during writing: '" << xmlFile.c_str() << "'\n"
<< "DOMException code is: " << toCatch.code << XERCES_STD_QUALIFIER endl;
if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))
XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;
errorOccurred = true;
}
catch (...)
{
XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during writing: '" << xmlFile.c_str() << "'\n";
errorOccurred = true;
}
return true;
}
bool XMLTools::loadFile(std::string xmlFile)
{
bool errorOccurred = false;
try
{
AbstractDOMParser::ValSchemes valScheme = AbstractDOMParser::Val_Never;
// initialize if not previously done
if ( m_parser == 0 )
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"
<< StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
return false;
}
// Instantiate the DOM parser.
static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
// check if not previously initialized
if ( m_parser == 0)
m_parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
DOMConfiguration *config = m_parser->getDomConfig();
config->setParameter(XMLUni::fgDOMNamespaces, false);
config->setParameter(XMLUni::fgXercesSchema, false);
config->setParameter(XMLUni::fgXercesSchemaFullChecking, false);
config->setParameter(XMLUni::fgDOMValidate, false);
// enable datatype normalization - default is off
config->setParameter(XMLUni::fgDOMDatatypeNormalization, false);
// And create our error handler and install it
DOMCustomErrorHandler errorHandler;
config->setParameter(XMLUni::fgDOMErrorHandler, &errorHandler);
unsigned long duration;
//reset error count first
errorHandler.resetErrors();
try
{
// reset document pool
m_parser->resetDocumentPool();
const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
m_doc = m_parser->parseURI(xmlFile.c_str());
const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
duration = endMillis - startMillis;
}
catch (const XMLException& toCatch)
{
XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << xmlFile.c_str() << "'\n"
<< "Exception message is: \n"
<< StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
errorOccurred = true;
}
catch (const DOMException& toCatch)
{
const unsigned int maxChars = 2047;
XMLCh errText[maxChars + 1];
XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << xmlFile.c_str() << "'\n"
<< "DOMException code is: " << toCatch.code << XERCES_STD_QUALIFIER endl;
if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))
XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;
errorOccurred = true;
}
catch (...)
{
XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during parsing: '" << xmlFile.c_str() << "'\n";
errorOccurred = true;
}
return true;
}
bool XMLTools::handleData(bool write, std::string &data, std::string tagName, int itemId)
{
DOMNodeList* _elemList = m_doc->getDocumentElement()->getElementsByTagName(XMLString::transcode(tagName.c_str()));
if ( _elemList->getLength() > 0 )
{
try
{
if ( !write)
data = XMLString::transcode(_elemList->item(itemId)->getTextContent());
else // read
_elemList->item(itemId)->setTextContent(XMLString::transcode(data.c_str()));
}
catch(...)
{
return false;
}
return true;
}
else // create the new tag
{
try
{
DOMElement* _rootElem = m_doc->getDocumentElement();
DOMElement* _newElem = m_doc->createElement(XMLString::transcode(tagName.c_str()));
_newElem->setTextContent(XMLString::transcode(data.c_str()));
_rootElem->appendChild(_newElem);
}
catch(...)
{
return false;
}
return true;
}
}
int XMLTools::numberOfElements(std::string tagName)
{
DOMNodeList* _elemList = m_doc->getDocumentElement()->getElementsByTagName(XMLString::transcode(tagName.c_str()));
return _elemList->getLength();
}
bool XMLTools::handleData(float &data, const std::string &tagName, const std::string &attributeName, const int &itemId)
{
DOMNodeList* _elemList = m_doc->getDocumentElement()->getElementsByTagName(XMLString::transcode(tagName.c_str()));
if ( _elemList->getLength() > 0 )
{
try
{
if ( _elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str())))
{
std::string s = XMLString::transcode(_elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str()))->getTextContent());
data = atof(s.c_str());
}
else
return false;
}
catch(...)
{
return false;
}
return true;
}
else
return false;
}
bool XMLTools::handleData(int &data, const std::string &tagName, const std::string &attributeName, const int &itemId)
{
DOMNodeList* _elemList = m_doc->getDocumentElement()->getElementsByTagName(XMLString::transcode(tagName.c_str()));
if ( _elemList->getLength() > 0 )
{
try
{
std::string s = XMLString::transcode(_elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str()))->getTextContent());
data = atoi(s.c_str());
}
catch(...)
{
return false;
}
return true;
}
else
return false;
}
bool XMLTools::handleData(bool write, std::string &data, const std::string &tagName, const std::string &attributeName, const int &itemId)
{
DOMNodeList* _elemList = m_doc->getDocumentElement()->getElementsByTagName(XMLString::transcode(tagName.c_str()));
std::string _tmp = "";
if ( _elemList->getLength() > 0 && _elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str())) != NULL )
_tmp = XMLString::transcode(_elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str()))->getTextContent());
if ( (!write && _elemList->getLength() > 0 && _elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str())) != NULL) || (_elemList->getLength() > 0 && _elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str())) != NULL && _tmp.compare(data) == 0))
{
try
{
data = XMLString::transcode(_elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str()))->getTextContent());
}
catch(...)
{
return false;
}
return true;
}
else // create the new tag
{
try
{
int _val = _elemList->getLength();
bool _found = false;
// check if the tag already exists ( if not create a new node)
/*for(int i=0;i<_elemList->getLength();i++)
{
if ( _elemList->item(i)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str())) != NULL )
{
std::string _tmp = XMLString::transcode(_elemList->item(itemId)->getAttributes()->getNamedItem(XMLString::transcode(attributeName.c_str()))->getTextContent());
if (_tmp.compare(attributeName) == 0)
{
_found = true;
}
}
}*/
_found = (_elemList->getLength() > 0 );
if ( !_found)
{
DOMElement* _rootElem = m_doc->getDocumentElement();
DOMElement* _newElem = m_doc->createElement(XMLString::transcode(tagName.c_str()));
_newElem->setAttribute(XMLString::transcode(attributeName.c_str()), XMLString::transcode(data.c_str()));
_rootElem->appendChild(_newElem);
}
else
{
DOMNode *_node = (_elemList->item(itemId));
DOMElement *_element = dynamic_cast<DOMElement*>(_node);
_element->setAttribute(XMLString::transcode(attributeName.c_str()), XMLString::transcode(data.c_str()));
}
}
catch(...)
{
return false;
}
return true;
}
}
void XMLTools::string2matrix(Eigen::Matrix4f &matrix, std::string &str)
{
Eigen::Matrix4f _tempMatrix;
boost::char_separator<char> sep(" \n\t");
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
tokenizer tok(str, sep);
float data[16];
int counter = 0;
for(tokenizer::iterator it = tok.begin();it != tok.end();++it)
{
data[counter++]=atof((*it).c_str());
}
_tempMatrix << Eigen::Map<Eigen::Matrix4f>(data);
matrix = _tempMatrix.transpose();
}
bool XMLTools::handleData(Eigen::Matrix4f &matrix, std::string tagName, int itemId)
{
Eigen::Matrix4f _tempMatrix;
DOMNodeList* _elemList = m_doc->getDocumentElement()->getElementsByTagName(XMLString::transcode(tagName.c_str()));
if ( _elemList->getLength() > 0 )
{
try
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
std::string s = XMLString::transcode(_elemList->item(itemId)->getTextContent());
boost::char_separator<char> sep(" \n\t");
tokenizer tok(s, sep);
float data[16];
int counter = 0;
for(tokenizer::iterator it = tok.begin();it != tok.end();++it)
{
data[counter++]=atof((*it).c_str());
}
_tempMatrix << Eigen::Map<Eigen::Matrix4f>(data);
matrix = _tempMatrix.transpose();
}
catch(...)
{
return false;
}
return true;
}
else
return false;
}
DOMCustomErrorHandler::DOMCustomErrorHandler() :
fSawErrors(false)
{
}
DOMCustomErrorHandler::~DOMCustomErrorHandler()
{
}
// ---------------------------------------------------------------------------
// DOMCountHandlers: Overrides of the DOM ErrorHandler interface
// ---------------------------------------------------------------------------
bool DOMCustomErrorHandler::handleError(const DOMError& domError)
{
fSawErrors = true;
if (domError.getSeverity() == DOMError::DOM_SEVERITY_WARNING)
XERCES_STD_QUALIFIER cerr << "\nWarning at file ";
else if (domError.getSeverity() == DOMError::DOM_SEVERITY_ERROR)
XERCES_STD_QUALIFIER cerr << "\nError at file ";
else
XERCES_STD_QUALIFIER cerr << "\nFatal Error at file ";
std::stringstream ss;
ss << StrX(domError.getLocation()->getURI())
<< ", line " << domError.getLocation()->getLineNumber()
<< ", char " << domError.getLocation()->getColumnNumber()
<< "\n Message: " << StrX(domError.getMessage()) << XERCES_STD_QUALIFIER endl;
QMessageBox msgBox;
msgBox.setText(ss.str().c_str());
msgBox.exec();
return true;
}
void DOMCustomErrorHandler::resetErrors()
{
fSawErrors = false;
}
bool XMLTools::createFile( std::string masterTag)
{
// Initialize the XML4C2 system.
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
char *pMsg = XMLString::transcode(toCatch.getMessage());
XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
<< " Exception message:"
<< pMsg;
XMLString::release(&pMsg);
return false;
}
static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
if (impl != NULL)
{
try
{
m_doc = impl->createDocument(
0, // root element namespace URI.
XMLString::transcode(masterTag.c_str()), // root element name
0); // document type object (DTD).
//DOMElement* rootElem = doc->getDocumentElement();
}
catch(...)
{
return false;
}
return true;
}
return false;
}