summaryrefslogtreecommitdiff
path: root/examples/cxx/tree/streaming/parser.cxx
blob: 5588f7a2e6baea221004f1df8d3c99daac8e28a5 (plain)
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
// file      : examples/cxx/tree/streaming/parser.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : not copyrighted - public domain

#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLString.hpp>

#include <xercesc/sax2/Attributes.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>

#include <xercesc/dom/DOM.hpp>

#if _XERCES_VERSION >= 30000
#  include <xercesc/dom/impl/DOMTextImpl.hpp>
#endif

#include <xsd/cxx/auto-array.hxx>

#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/xml/sax/bits/error-handler-proxy.hxx>

#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/error-handler.hxx>

#include "parser.hxx"

using namespace std;
using namespace xercesc;

namespace xml = xsd::cxx::xml;
namespace tree = xsd::cxx::tree;

class parser_impl: DefaultHandler
{
public:
  parser_impl ();

  xml::dom::auto_ptr<DOMDocument>
  start (istream& is, const string& id, bool validate);

  xml::dom::auto_ptr<DOMDocument>
  next ();

  // SAX event handlers.
  //
private:
  virtual void
  startElement (const XMLCh* const uri,
                const XMLCh* const lname,
                const XMLCh* const qname,
                const Attributes& attributes);

  virtual void
  endElement (const XMLCh* const uri,
              const XMLCh* const lname,
              const XMLCh* const qname);

  virtual void
  characters (const XMLCh* const s,
#if _XERCES_VERSION >= 30000
              const XMLSize_t length
#else
              const unsigned int length
#endif
  );

private:
  // SAX parser.
  //
  bool clean_;
  auto_ptr<SAX2XMLReader> parser_;
  XMLPScanToken token_;
  tree::error_handler<char> error_handler_;
  xml::sax::bits::error_handler_proxy<char> error_proxy_;
  auto_ptr<xml::sax::std_input_source> isrc_;

  size_t depth_;

  // DOM document being built.
  //
  DOMImplementation& dom_impl_;
  xml::dom::auto_ptr<DOMDocument> doc_;
  DOMElement* cur_;
};

const XMLCh ls[] = {chLatin_L, chLatin_S, chNull};

parser_impl::
parser_impl ()
    : clean_ (true),
      parser_ (XMLReaderFactory::createXMLReader ()),
      error_proxy_ (error_handler_),
      dom_impl_ (*DOMImplementationRegistry::getDOMImplementation (ls))
{
  parser_->setFeature (XMLUni::fgSAX2CoreNameSpaces, true);
  parser_->setFeature (XMLUni::fgSAX2CoreNameSpacePrefixes, true);
  parser_->setFeature (XMLUni::fgXercesValidationErrorAsFatal, true);
  parser_->setFeature (XMLUni::fgXercesSchemaFullChecking, false);

  // Xerces-C++ 3.1.0 is the first version with working multi import
  // support. It also allows us to disable buffering in the parser
  // so that the date is parsed and returned as soon as it is
  // available.
  //
#if _XERCES_VERSION >= 30100
  parser_->setFeature (XMLUni::fgXercesHandleMultipleImports, true);

  XMLSize_t lwm = 0;
  parser_->setProperty (XMLUni::fgXercesLowWaterMark, &lwm);
#endif

  parser_->setErrorHandler (&error_proxy_);
  parser_->setContentHandler (this);
}

xml::dom::auto_ptr<DOMDocument> parser_impl::
start (istream& is, const string& id, bool val)
{
  // Reset our state.
  //
  depth_ = 0;
  doc_.reset ();
  error_handler_.reset ();

  if (!clean_)
    parser_->parseReset (token_);
  else
    clean_ = false;

  isrc_.reset (new xml::sax::std_input_source (is, id));

  parser_->setFeature (XMLUni::fgSAX2CoreValidation, val);
  parser_->setFeature (XMLUni::fgXercesSchema, val);

  // Start parsing. The first document that we return is a "carcase"
  // of the complete document. That is, the root element with all the
  // attributes but without any content.
  //
  bool r (parser_->parseFirst (*isrc_, token_));
  error_handler_.throw_if_failed<tree::parsing<char> > ();

  while (r && depth_ == 0)
  {
    r = parser_->parseNext (token_);
    error_handler_.throw_if_failed<tree::parsing<char> > ();
  }

  if (!r)
    return xml::dom::auto_ptr<DOMDocument> (0);

  return doc_;
}

xml::dom::auto_ptr<DOMDocument> parser_impl::
next ()
{
  // We should be at depth 1. If not, then we are done parsing.
  //
  if (depth_ != 1)
    return xml::dom::auto_ptr<DOMDocument> (0);

  bool r (true);

  // Keep calling parseNext() until we either move to a greater depth or
  // get a document. This way we skip the text (presumably whitespaces)
  // that may be preceding the next chunk.
  //
  while (r && depth_ == 1 && doc_.get () == 0)
  {
    parser_->parseNext (token_);
    error_handler_.throw_if_failed<tree::parsing<char> > ();
  }

  if (!r)
    return xml::dom::auto_ptr<DOMDocument> (0);

  // If we are not at depth 1, keep calling parseNext() until we get
  // there.
  //
  while (r && depth_ != 1)
  {
    r = parser_->parseNext (token_);
    error_handler_.throw_if_failed<tree::parsing<char> > ();
  }

  if (!r)
    return xml::dom::auto_ptr<DOMDocument> (0);

  return doc_;
}

// DOM builder.
//

void parser_impl::
startElement (const XMLCh* const uri,
              const XMLCh* const /*lname*/,
              const XMLCh* const qname,
              const Attributes& attr)
{
  if (doc_.get () == 0)
  {
    doc_.reset (dom_impl_.createDocument (uri, qname, 0));
    cur_ = doc_->getDocumentElement ();
  }
  else
  {
    DOMElement* e = doc_->createElementNS (uri, qname);
    cur_->appendChild (e);
    cur_ = e;
  }

  // Set attributes.
  //
#if _XERCES_VERSION >= 30000
  for (XMLSize_t i (0), end (attr.getLength()); i < end; ++i)
#else
  for (unsigned int i (0), end (attr.getLength()); i < end; ++i)
#endif
  {
    cur_->setAttributeNS (attr.getURI (i),
                          attr.getQName (i),
                          attr.getValue (i));
  }

  depth_++;
}

void parser_impl::
endElement (const XMLCh* const /*uri*/,
            const XMLCh* const /*lname*/,
            const XMLCh* const /*qname*/)
{
  // We have an element parent only on depth 2 or greater.
  //
  if (--depth_ > 1)
    cur_ = static_cast<DOMElement*> (cur_->getParentNode ());
}

#if _XERCES_VERSION >= 30000
void parser_impl::
characters (const XMLCh* const s, const XMLSize_t length)
{
  const XMLCh empty[] = {chNull};

  // Ignore text content (presumably whitespaces) in the root element.
  //
  if (depth_ > 1)
  {
    DOMText* t = doc_->createTextNode (empty);
    static_cast<DOMTextImpl*> (t)->appendData (s, length);
    cur_->appendChild (t);
  }
}
#else
void parser_impl::
characters (const XMLCh* const s, const unsigned int length)
{
  // Ignore text content (presumably whitespaces) in the root element.
  //
  if (depth_ > 1)
  {
    // For Xerces-C++ 2-series we have to make copy.
    //
    xsd::cxx::auto_array<XMLCh> tmp (new XMLCh[length + 1]);
    XMLString::copyNString (tmp.get (), s, length);
    cur_->appendChild (doc_->createTextNode (tmp.get ()));
  }
}
#endif


//
// parser
//

parser::
~parser ()
{
}

parser::
parser ()
    : impl_ (new parser_impl)
{
}

xml::dom::auto_ptr<DOMDocument> parser::
start (istream& is, const string& id, bool val)
{
  return impl_->start (is, id, val);
}

xml::dom::auto_ptr<DOMDocument> parser::
next ()
{
  return impl_->next ();
}