aboutsummaryrefslogtreecommitdiff
path: root/examples/hybrid/dom.cxx
blob: cd1e0e096ad0fdf958823c47fbeb7d22f95943e1 (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
// file      : examples/hybrid/dom.cxx
// copyright : not copyrighted - public domain

#include <xml/parser.hxx>
#include <xml/serializer.hxx>

#include "dom.hxx"

using namespace std;
using namespace xml;

static bool
whitespace (const string& s)
{
  for (string::size_type i (0); i < s.size (); ++i)
  {
    char c (s[i]);
    if (c != 0x20 && c != 0x0A && c != 0x0D && c != 0x09)
      return false;
  }

  return true;
}

element::
element (parser& p, bool se)
{
  if (se)
    p.next_expect (parser::start_element);

  name_ = p.qname ();

  // Extract attributes.
  //
  const parser::attribute_map_type& m (p.attribute_map ());
  for (parser::attribute_map_type::const_iterator i (m.begin ());
       i != m.end ();
       ++i)
    attributes_[i->first] = i->second.value;

  // Parse content (nested elements or text).
  //
  while (p.peek () != parser::end_element)
  {
    switch (p.next ())
    {
    case parser::start_element:
      {
        if (!text_.empty ())
        {
          if (!whitespace (text_))
            throw parsing (p, "element in simple content");

          text_.clear ();
        }

        elements_.push_back (element (p, false));
        p.next_expect (parser::end_element);

        break;
      }
    case parser::characters:
      {
        if (!elements_.empty ())
        {
          if (!whitespace (p.value ()))
            throw parsing (p, "characters in complex content");

          break; // Ignore whitespaces.
        }

        text_ += p.value ();
        break;
      }
    default:
      break; // Ignore any other events.
    }
  }

  if (se)
    p.next_expect (parser::end_element);
}

void element::
serialize (serializer& s, bool se) const
{
  if (se)
    s.start_element (name_);

  // Add attributes.
  //
  for (attributes_type::const_iterator i (attributes_.begin ());
       i != attributes_.end ();
       ++i)
  {
    s.attribute (i->first, i->second);
  }

  // Serialize content (nested elements or text).
  //
  if (!elements_.empty ())
  {
    for (elements_type::const_iterator i (elements_.begin ());
         i != elements_.end ();
         ++i)
    {
      i->serialize (s);
    }
  }
  else if (!text_.empty ())
    s.characters (text_);

  if (se)
    s.end_element ();
}