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 xmlNodeSetContentLen(node, 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 xmlFreeNodeList(node->children);
66 node->children = node->last = NULL;
68 for (auto child : new_nodes) {
69 xmlAddChild(node, child);
76 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
77 : substitution_map(substitution_map) {}
79 Substitute::Substitute(initializer_list<pair<const string, Directive*>> substitution_map)
80 : substitution_map(substitution_map) {}
82 Substitute::~Substitute()
84 for (auto it : substitution_map) {
89 void Substitute::process(xmlNode *node, bool clean)
91 for (xmlNode *child = node->children; child != NULL; child = child->next) {
92 bool processed = false;
94 if (child->type == XML_ELEMENT_NODE) {
95 // Find the ID, if any.
97 for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
98 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
99 strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
100 id = reinterpret_cast<const char *>(xmlNodeGetContent(attr->children));
103 if (attr->prev == NULL) {
104 child->properties = attr->next;
106 attr->prev->next = attr->next;
112 // Check all substitutions to see if we found anything appropriate.
113 for (auto it : substitution_map) {
114 if (it.first == reinterpret_cast<const char *>(child->name) ||
115 (!id.empty() && it.first == ("#" + id))) {
116 it.second->process(child, clean);
124 process(child, clean);
132 void process_file(const string &input_filename,
133 const string &output_filename,
134 Directive *root_directive)
138 xmlDocPtr doc = xmlParseFile(input_filename.c_str());
139 root_directive->process(xmlDocGetRootElement(doc), true);
140 xmlSaveFile(output_filename.c_str(), doc);