src/XMLTableCommand.h
author František Kučera <franta-hg@frantovo.cz>
Tue, 22 Oct 2019 19:53:46 +0200
branchv_0
changeset 4 a0689654b3c2
parent 2 0d3eb5129582
child 7 ff69af3c67a3
permissions -rw-r--r--
fix license version: GNU GPLv3

/**
 * Relational pipes
 * Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

#include <libxml++-2.6/libxml++/libxml++.h>

#include <relpipe/writer/typedefs.h>

#include "Configuration.h"

namespace relpipe {
namespace in {
namespace xmltable {

using namespace relpipe::writer;

class XMLCommand {
private:
	std::wstring_convert<codecvt_utf8<wchar_t>> convertor; // TODO: support also other encodings.

public:

	void process(std::istream& input, std::ostream& output, Configuration& configuration) {
		std::shared_ptr<RelationalWriter> writer(Factory::create(output));

		xmlpp::DomParser parser;
		parser.parse_stream(input);
		xmlpp::Element* root = parser.get_document()->get_root_node();

		xmlpp::Node::PrefixNsMap ns;
		for (int i = 0; i < configuration.namespaceMappings.size(); i++) {
			std::string prefix = convertor.to_bytes(configuration.namespaceMappings[i]);
			std::string uri = convertor.to_bytes(configuration.namespaceMappings[++i]);
			ns[prefix] = uri;
		}

		for (const RelationConfiguration& r : configuration.relationConfigurations) {
			std::vector<relpipe::writer::AttributeMetadata> attributesMetadata;
			for (AttributeRecipe a : r.attributes) attributesMetadata.push_back(AttributeMetadata{a.name, a.type});
			relpipe::writer::string_t name = r.nameIsXPath ? convertor.from_bytes(root->eval_to_string(convertor.to_bytes(r.relation), ns)) : r.relation;
			writer->startRelation(name, attributesMetadata, true);
			for (xmlpp::Node* n : root->find(convertor.to_bytes(r.xpath), ns)) {
				for (AttributeRecipe a : r.attributes) {
					// TODO: convert to bytes only once
					writer->writeAttribute(convertor.from_bytes(n->eval_to_string(convertor.to_bytes(a.xpath), ns)));
				}
			}
		}
	}
};

}
}
}