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;
19 frag->last = node->last;
25 Directive::~Directive() {}
27 Replace::Replace(const string &str)
30 void Replace::process(xmlNode *node, bool clean) {
31 xmlNodeSetContentLen(node, reinterpret_cast<const xmlChar *>(str.data()), str.size());
37 Clone::Clone(const vector<Directive *> &subdirectives)
38 : subdirectives(subdirectives) {}
40 Clone::Clone(initializer_list<Directive *> subdirectives)
41 : subdirectives(subdirectives) {}
45 for (auto it : subdirectives) {
50 void Clone::process(xmlNode *node, bool clean)
52 // We can't use xmlNewDocFragment, since xmlDOMWrapCloneNode only knows
53 // how to clone elements.
54 vector<xmlNode *> new_nodes;
56 for (auto it : subdirectives) {
58 xmlDOMWrapCloneNode(NULL, node->doc, node, &new_node, node->doc, NULL, 1, 0);
59 it->process(new_node, clean);
60 for (xmlNode *child = new_node->children; child != NULL; child = child->next) {
61 new_nodes.push_back(child);
65 xmlFreeNodeList(node->children);
67 node->children = node->last = NULL;
69 for (auto child : new_nodes) {
70 xmlAddChild(node, child);
77 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
78 : substitution_map(substitution_map) {}
80 Substitute::Substitute(initializer_list<pair<const string, Directive*>> substitution_map)
81 : substitution_map(substitution_map) {}
83 Substitute::~Substitute()
85 for (auto it : substitution_map) {
90 void Substitute::process(xmlNode *node, bool clean)
92 for (xmlNode *child = node->children; child != NULL; child = child->next) {
93 bool processed = false;
95 if (child->type == XML_ELEMENT_NODE) {
96 // Find the ID, if any.
98 xmlAttr *id_attr = NULL;
99 for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
100 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
101 strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
102 xmlChar *id_buf = xmlNodeGetContent(attr->children);
103 id = reinterpret_cast<const char *>(id_buf);
108 if (clean && id_attr != NULL) {
109 xmlRemoveProp(id_attr);
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);