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 Replace::Replace(const string &str)
27 void Replace::process(xmlNode *node, bool clean) {
28 node->children = xmlNewTextLen(reinterpret_cast<const xmlChar *>(str.data()), str.size());
34 Clone::Clone(const vector<Directive *> &subdirectives)
35 : subdirectives(subdirectives) {}
37 Clone::Clone(initializer_list<Directive *> subdirectives)
38 : subdirectives(subdirectives) {}
40 void Clone::process(xmlNode *node, bool clean)
42 // We can't use xmlNewDocFragment, since xmlDOMWrapCloneNode only knows
43 // how to clone elements.
44 vector<xmlNode *> new_nodes;
46 for (auto it : subdirectives) {
48 xmlDOMWrapCloneNode(NULL, node->doc, node, &new_node, node->doc, NULL, 1, 0);
49 it->process(new_node, clean);
50 for (xmlNode *child = new_node->children; child != NULL; child = child->next) {
51 new_nodes.push_back(child);
55 node->children = NULL;
56 for (auto child : new_nodes) {
57 xmlAddChild(node, child);
64 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
65 : substitution_map(substitution_map) {}
67 Substitute::Substitute(initializer_list<pair<const string, Directive*>> substitution_map)
68 : substitution_map(substitution_map) {}
70 void Substitute::process(xmlNode *node, bool clean)
72 for (xmlNode *child = node->children; child != NULL; child = child->next) {
73 bool processed = false;
75 if (child->type == XML_ELEMENT_NODE) {
76 // Find the ID, if any.
78 for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
79 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
80 strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
81 id = reinterpret_cast<const char *>(xmlNodeGetContent(attr->children));
84 if (attr->prev == NULL) {
85 child->properties = attr->next;
87 attr->prev->next = attr->next;
93 // Check all substitutions to see if we found anything appropriate.
94 for (auto it : substitution_map) {
95 if (it.first == reinterpret_cast<const char *>(child->name) ||
96 (!id.empty() && it.first == ("#" + id))) {
97 it.second->process(child, clean);
105 process(child, clean);
113 void process_file(const string &input_filename,
114 const string &output_filename,
115 Directive *root_directive)
119 xmlDocPtr doc = xmlParseFile(input_filename.c_str());
120 root_directive->process(xmlDocGetRootElement(doc), true);
121 xmlSaveFile(output_filename.c_str(), doc);