IBR-DTNSuite  0.10
XMLStreamReader.cpp
Go to the documentation of this file.
1 /*
2  * XMLStreamReader.cpp
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
23 #include "ibrcommon/Exceptions.h"
24 #include <string.h>
25 
26 namespace ibrcommon
27 {
29  : _callback(callback)
30  { }
31 
33  { }
34 
36  {
37  XMLStreamHandler *cb = static_cast<XMLStreamHandler*>(data);
38  cb->startDocument();
39  }
40 
42  {
43  XMLStreamHandler *cb = static_cast<XMLStreamHandler*>(data);
44  cb->endDocument();
45  }
46 
47  void XMLStreamReader::__startElement(void *data, const xmlChar *fullname, const xmlChar **ats)
48  {
49  XMLStreamHandler *cb = static_cast<XMLStreamHandler*>(data);
50  std::map<std::string, std::string> attrs;
51 
52  if (ats != NULL)
53  {
54  int i = 0;
55  while (ats[i] != NULL)
56  {
57  attrs[std::string((const char*)ats[i])] = std::string((const char*)ats[i+1]);
58  i += 2;
59  }
60  }
61 
62  const std::string name((const char*)fullname);
63  cb->startElement(name, attrs);
64  }
65 
66  void XMLStreamReader::__endElement(void *data, const xmlChar *fullname)
67  {
68  XMLStreamHandler *cb = static_cast<XMLStreamHandler*>(data);
69  const std::string name((const char*)fullname);
70  cb->endElement(name);
71  }
72 
73  void XMLStreamReader::__characters(void *data, const xmlChar *ch, int len)
74  {
75  XMLStreamHandler *cb = static_cast<XMLStreamHandler*>(data);
76  cb->characters((const char*)ch, len);
77  }
78 
79  void XMLStreamReader::parse(std::istream &stream)
80  {
81  xmlSAXHandler my_handler;
82  ::memset(&my_handler, '\0', sizeof(xmlSAXHandler));
83 
84  my_handler.startDocument = __startDocument;
85  my_handler.endDocument = __endDocument;
86  my_handler.startElement = __startElement;
87  my_handler.endElement = __endElement;
88  my_handler.characters = __characters;
89 
90  int res = 0, size = 1024;
91  char chars[1024];
92  xmlParserCtxtPtr ctx = xmlCreatePushParserCtxt(&my_handler, &_callback, chars, res, NULL);
93 
94  while (stream.good())
95  {
96  stream.read(chars, size);
97 
98  if (stream.eof())
99  {
100  xmlParseChunk(ctx, chars, static_cast<int>(stream.gcount()), 1);
101  }
102  else
103  {
104  xmlParseChunk(ctx, chars, static_cast<int>(stream.gcount()), 0);
105  }
106  }
107  }
108 
109 }