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
|
#include "Node.h"
#include <mutex>
#include "Document.h"
namespace xml
{
bool Node::isValid() const
{
return _xmlNode;
}
std::string Node::getName() const
{
std::lock_guard lock(_owner->getLock());
if (_xmlNode) {
return _xmlNode.name();
}
return {};
}
NodeList Node::getChildren() const
{
// Lock the document to collect the children
std::lock_guard lock(_owner->getLock());
NodeList retval;
for (auto i = _xmlNode.begin(); i != _xmlNode.end(); ++i) {
retval.emplace_back(_owner, *i);
}
return retval;
}
Node Node::createChild(const std::string& name)
{
std::lock_guard lock(_owner->getLock());
// Create a new child under the contained node
auto newChild = _xmlNode.append_child(name.c_str());
// Create a new xml::Node out of this pointer and return it
return Node(_owner, newChild);
}
NodeList Node::getNamedChildren(const std::string& name) const
{
std::lock_guard lock(_owner->getLock());
NodeList retval;
// Iterate throught the list of children, adding each child node to the return list if
// it matches the requested name
for (auto i = _xmlNode.begin(); i != _xmlNode.end(); ++i) {
if (i->name() == name) {
retval.emplace_back(_owner, *i);
}
}
return retval;
}
void Node::setAttributeValue(const std::string& key, const std::string& value)
{
std::lock_guard lock(_owner->getLock());
pugi::xml_attribute attr = _xmlNode.attribute(key.c_str());
if (!attr)
attr = _xmlNode.append_attribute(key.c_str());
attr.set_value(value.c_str());
}
void Node::removeAttribute(const std::string& key)
{
std::lock_guard lock(_owner->getLock());
_xmlNode.remove_attribute(key.c_str());
}
std::string Node::getAttributeValue(const std::string& key) const
{
std::lock_guard lock(_owner->getLock());
pugi::xml_attribute attr = _xmlNode.attribute(key.c_str());
if (attr)
return attr.value();
else
return {};
}
std::string Node::getContent() const
{
std::lock_guard lock(_owner->getLock());
return _xmlNode.text().get();
}
void Node::setContent(const std::string& content)
{
std::lock_guard lock(_owner->getLock());
_xmlNode.text() = content.c_str();
}
void Node::addText(const std::string& text)
{
std::lock_guard lock(_owner->getLock());
// Add a PCDATA node as a sibling following this node
auto textNode = _xmlNode.parent().insert_child_after(pugi::node_pcdata, _xmlNode);
textNode.set_value(text.c_str());
}
void Node::erase()
{
std::lock_guard lock(_owner->getLock());
_xmlNode.parent().remove_child(_xmlNode);
}
pugi::xml_node Node::getNodePtr() const
{
return _xmlNode;
}
} // namespace xml
|