]> git.sesse.net Git - xml-template/blob - c++0x/xml-template.cpp
Move the C++0x file processing logic into a shared function.
[xml-template] / c++0x / xml-template.cpp
1 #include "xml-template.h"
2
3 #include <string.h>
4 #include <libxml/parser.h>
5
6 using namespace std;
7
8 Replace::Replace(const string &str)
9         : str(str) {}
10
11 void Replace::process(xmlNode *node, bool clean) {
12         node->children = xmlNewTextLen(reinterpret_cast<const xmlChar *>(str.data()), str.size());
13 }
14
15 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
16         : substitution_map(substitution_map) {}
17
18 void Substitute::process(xmlNode *node, bool clean) {
19         for (xmlNode *child = node->children; child != NULL; child = child->next) {
20                 bool processed = false;
21
22                 if (child->type == XML_ELEMENT_NODE) {
23                         // Find the ID, if any.
24                         string id;
25                         for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
26                                 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
27                                     strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
28                                         id = reinterpret_cast<const char *>(xmlNodeGetContent(attr->children));
29                                 }
30                         }
31
32                         // Check all substitutions to see if we found anything appropriate.
33                         for (auto it : substitution_map) {
34                                 if (it.first == reinterpret_cast<const char *>(child->name) ||
35                                     (!id.empty() && it.first == ("#" + id))) {
36                                         it.second->process(child, clean);
37                                         processed = true;
38                                         break;
39                                 }
40                         }
41                 }
42                 
43                 if (!processed) {
44                         process(child, clean);
45                 }
46         }
47 }
48         
49 void process_file(const string &input_filename,
50                   const string &output_filename,
51                   Directive *root_directive)
52 {
53         LIBXML_TEST_VERSION
54
55         xmlDocPtr doc = xmlParseFile(input_filename.c_str());
56         root_directive->process(xmlDocGetRootElement(doc), false);
57         xmlSaveFile(output_filename.c_str(), doc);
58
59         xmlCleanupParser();
60         xmlMemoryDump();
61 }