xmpp_stanza.cpp 2.22 KB
Newer Older
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
#include <xmpp/xmpp_stanza.hpp>

#include <iostream>

XmlNode::XmlNode(const std::string& name, XmlNode* parent):
  name(name),
  parent(parent),
  closed(false)
{
}

XmlNode::XmlNode(const std::string& name):
  XmlNode(name, nullptr)
{
}

XmlNode::~XmlNode()
{
  this->delete_all_children();
}

void XmlNode::delete_all_children()
{
  for (auto& child: this->children)
    {
      delete child;
    }
  this->children.clear();
}

void XmlNode::set_attribute(const std::string& name, const std::string& value)
{
  this->attributes[name] = value;
}

void XmlNode::set_tail(const std::string& data)
{
  this->tail = data;
}

void XmlNode::set_inner(const std::string& data)
{
  this->inner = data;
}

void XmlNode::add_child(XmlNode* child)
{
  this->children.push_back(child);
}

void XmlNode::add_child(XmlNode&& child)
{
  XmlNode* new_node = new XmlNode(std::move(child));
  this->add_child(new_node);
}

XmlNode* XmlNode::get_last_child() const
{
  return this->children.back();
}

void XmlNode::close()
{
  if (this->closed)
    throw std::runtime_error("Closing an already closed XmlNode");
  this->closed = true;
}

XmlNode* XmlNode::get_parent() const
{
  return this->parent;
}

const std::string& XmlNode::get_name() const
{
  return this->name;
}

std::string XmlNode::to_string() const
{
  std::string res("<");
  res += this->name;
  for (const auto& it: this->attributes)
    res += " " + it.first + "='" + it.second + "'";
  if (this->closed && !this->has_children() && this->inner.empty())
    res += "/>";
  else
    {
      res += ">" + this->inner;
      for (const auto& child: this->children)
        res += child->to_string();
      if (this->closed)
        {
          res += "</" + this->name + ">";
        }
    }
  res += this->tail;
  return res;
}

void XmlNode::display() const
{
  std::cout << this->to_string() << std::endl;
}

bool XmlNode::has_children() const
{
  return !this->children.empty();
}

const std::string& XmlNode::operator[](const std::string& name) const
{
  try
    {
      const auto& value = this->attributes.at(name);
      return value;
    }
  catch (const std::out_of_range& e)
    {
      throw AttributeNotFound();
    }
}

std::string& XmlNode::operator[](const std::string& name)
{
  return this->attributes[name];
}