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 void Clone::process(xmlNode *node, bool clean) {
38 // We can't use xmlNewDocFragment, since xmlDOMWrapCloneNode only knows
39 // how to clone elements.
40 vector<xmlNode *> new_nodes;
42 for (auto it : subdirectives) {
44 xmlDOMWrapCloneNode(NULL, node->doc, node, &new_node, node->doc, NULL, 1, 0);
45 it->process(new_node, clean);
46 for (xmlNode *child = new_node->children; child != NULL; child = child->next) {
47 new_nodes.push_back(child);
51 node->children = NULL;
52 for (auto child : new_nodes) {
53 xmlAddChild(node, child);
60 Substitute::Substitute(const unordered_map<string, Directive*> &substitution_map)
61 : substitution_map(substitution_map) {}
63 void Substitute::process(xmlNode *node, bool clean) {
64 for (xmlNode *child = node->children; child != NULL; child = child->next) {
65 bool processed = false;
67 if (child->type == XML_ELEMENT_NODE) {
68 // Find the ID, if any.
70 for (xmlAttr *attr = child->properties; attr != NULL; attr = attr->next) {
71 if (strcmp(reinterpret_cast<const char *>(attr->ns->href), "http://template.sesse.net/") == 0 &&
72 strcmp(reinterpret_cast<const char *>(attr->name), "id") == 0) {
73 id = reinterpret_cast<const char *>(xmlNodeGetContent(attr->children));
76 if (attr->prev == NULL) {
77 child->properties = attr->next;
79 attr->prev->next = attr->next;
85 // Check all substitutions to see if we found anything appropriate.
86 for (auto it : substitution_map) {
87 if (it.first == reinterpret_cast<const char *>(child->name) ||
88 (!id.empty() && it.first == ("#" + id))) {
89 it.second->process(child, clean);
97 process(child, clean);
105 void process_file(const string &input_filename,
106 const string &output_filename,
107 Directive *root_directive)
111 xmlDocPtr doc = xmlParseFile(input_filename.c_str());
112 root_directive->process(xmlDocGetRootElement(doc), true);
113 xmlSaveFile(output_filename.c_str(), doc);