]> git.sesse.net Git - xml-template/blob - c++0x/xml-template.cpp
Split out the C++0x library into a separate file from the simple unit test.
[xml-template] / c++0x / xml-template.cpp
1 #include "xml-template.h"
2
3 #include <string.h>
4
5 using namespace std;
6
7 Replace::Replace(const string &str)
8         : str(str) {}
9
10 void Replace::process(xmlNode *node, bool clean) {
11         node->children = xmlNewTextLen(reinterpret_cast<const xmlChar *>(str.data()), str.size());
12 }
13
14 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
15         : substitution_map(substitution_map) {}
16
17 void Substitute::process(xmlNode *node, bool clean) {
18         for (xmlNode *child = node->children; child != NULL; child = child->next) {
19                 bool processed = false;
20
21                 if (child->type == XML_ELEMENT_NODE) {
22                         // Find the ID, if any.
23                         string id;
24                         for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
25                                 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
26                                     strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
27                                         id = reinterpret_cast<const char *>(xmlNodeGetContent(attr->children));
28                                 }
29                         }
30
31                         // Check all substitutions to see if we found anything appropriate.
32                         for (auto it : substitution_map) {
33                                 if (it.first == reinterpret_cast<const char *>(child->name) ||
34                                     (!id.empty() && it.first == ("#" + id))) {
35                                         it.second->process(child, clean);
36                                         processed = true;
37                                         break;
38                                 }
39                         }
40                 }
41                 
42                 if (!processed) {
43                         process(child, clean);
44                 }
45         }
46 }