1 #include "xml-template.h"
4 #include <libxml/parser.h>
10 void clean_node(xmlNode *node)
12 if (node->type != XML_ELEMENT_NODE) {
15 if (strcmp(reinterpret_cast<const char *>(node->ns->href), "http://template.sesse.net/") == 0) {
16 xmlNode *frag = xmlNewDocFragment(node->doc);
17 xmlReplaceNode(node, frag);
18 frag->children = node->children;
24 Directive::~Directive() {}
26 Replace::Replace(const string &str)
29 void Replace::process(xmlNode *node, bool clean) {
30 node->children = xmlNewTextLen(reinterpret_cast<const xmlChar *>(str.data()), str.size());
36 Clone::Clone(const vector<Directive *> &subdirectives)
37 : subdirectives(subdirectives) {}
39 Clone::Clone(initializer_list<Directive *> subdirectives)
40 : subdirectives(subdirectives) {}
44 for (auto it : subdirectives) {
49 void Clone::process(xmlNode *node, bool clean)
51 // We can't use xmlNewDocFragment, since xmlDOMWrapCloneNode only knows
52 // how to clone elements.
53 vector<xmlNode *> new_nodes;
55 for (auto it : subdirectives) {
57 xmlDOMWrapCloneNode(NULL, node->doc, node, &new_node, node->doc, NULL, 1, 0);
58 it->process(new_node, clean);
59 for (xmlNode *child = new_node->children; child != NULL; child = child->next) {
60 new_nodes.push_back(child);
64 node->children = NULL;
65 for (auto child : new_nodes) {
66 xmlAddChild(node, child);
73 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
74 : substitution_map(substitution_map) {}
76 Substitute::Substitute(initializer_list<pair<const string, Directive*>> substitution_map)
77 : substitution_map(substitution_map) {}
79 Substitute::~Substitute()
81 for (auto it : substitution_map) {
86 void Substitute::process(xmlNode *node, bool clean)
88 for (xmlNode *child = node->children; child != NULL; child = child->next) {
89 bool processed = false;
91 if (child->type == XML_ELEMENT_NODE) {
92 // Find the ID, if any.
94 for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
95 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
96 strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
97 id = reinterpret_cast<const char *>(xmlNodeGetContent(attr->children));
100 if (attr->prev == NULL) {
101 child->properties = attr->next;
103 attr->prev->next = attr->next;
109 // Check all substitutions to see if we found anything appropriate.
110 for (auto it : substitution_map) {
111 if (it.first == reinterpret_cast<const char *>(child->name) ||
112 (!id.empty() && it.first == ("#" + id))) {
113 it.second->process(child, clean);
121 process(child, clean);
129 void process_file(const string &input_filename,
130 const string &output_filename,
131 Directive *root_directive)
135 xmlDocPtr doc = xmlParseFile(input_filename.c_str());
136 root_directive->process(xmlDocGetRootElement(doc), true);
137 xmlSaveFile(output_filename.c_str(), doc);