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 std::vector<Directive *> &subdirectives)
35 : subdirectives(subdirectives) {}
37 Clone::Clone(std::initializer_list<Directive *> subdirectives)
38 : subdirectives(subdirectives) {}
40 void Clone::process(xmlNode *node, bool clean) {
41 // We can't use xmlNewDocFragment, since xmlDOMWrapCloneNode only knows
42 // how to clone elements.
43 vector<xmlNode *> new_nodes;
45 for (auto it : subdirectives) {
47 xmlDOMWrapCloneNode(NULL, node->doc, node, &new_node, node->doc, NULL, 1, 0);
48 it->process(new_node, clean);
49 for (xmlNode *child = new_node->children; child != NULL; child = child->next) {
50 new_nodes.push_back(child);
54 node->children = NULL;
55 for (auto child : new_nodes) {
56 xmlAddChild(node, child);
63 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
64 : substitution_map(substitution_map) {}
66 Substitute::Substitute(std::initializer_list<std::pair<const std::string, Directive*>> substitution_map)
67 : substitution_map(substitution_map) {}
69 void Substitute::process(xmlNode *node, bool clean) {
70 for (xmlNode *child = node->children; child != NULL; child = child->next) {
71 bool processed = false;
73 if (child->type == XML_ELEMENT_NODE) {
74 // Find the ID, if any.
76 for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
77 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
78 strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
79 id = reinterpret_cast<const char *>(xmlNodeGetContent(attr->children));
82 if (attr->prev == NULL) {
83 child->properties = attr->next;
85 attr->prev->next = attr->next;
91 // Check all substitutions to see if we found anything appropriate.
92 for (auto it : substitution_map) {
93 if (it.first == reinterpret_cast<const char *>(child->name) ||
94 (!id.empty() && it.first == ("#" + id))) {
95 it.second->process(child, clean);
103 process(child, clean);
111 void process_file(const string &input_filename,
112 const string &output_filename,
113 Directive *root_directive)
117 xmlDocPtr doc = xmlParseFile(input_filename.c_str());
118 root_directive->process(xmlDocGetRootElement(doc), true);
119 xmlSaveFile(output_filename.c_str(), doc);