aboutsummaryrefslogtreecommitdiff
path: root/src/function/write_file.cc
blob: 024a87a594911358e7d93b3014da0a0e127063e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "write_file.h"

#include <xalanc/PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <xalanc/PlatformSupport/XalanStdOutputStream.hpp>
#include <xalanc/XMLSupport/FormatterToXML.hpp>
#include <xalanc/XMLSupport/FormatterTreeWalker.hpp>

#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMElement.hpp>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#include "support/xalan_string.h"
#include "support/xerces_string_guard.h"
#include "support/dom/result_node_facade.h"

namespace {

bool serializeNodeToFile(
	const boost::filesystem::path& filePath,
	xalan::XalanNode* const        contentNode
) {
	const xalan::XalanNode::NodeType contentType(
		contentNode->getNodeType()
	);

	if ( contentType != xalan::XalanNode::DOCUMENT_NODE &&
	     contentType != xalan::XalanNode::ATTRIBUTE_NODE ) {
		boost::filesystem::ofstream file(filePath);

		if ( file.is_open() ) {
			if ( contentType == xalan::XalanNode::TEXT_NODE ) {
				file << InputXSLT::toString(contentNode->getNodeValue());
			} else {
				xalan::XalanStdOutputStream outputStream(file);
				xalan::XalanOutputStreamPrintWriter outputWriter(outputStream);

				xalan::FormatterToXML formatter(outputWriter);
				xalan::FormatterTreeWalker walker(formatter);

				formatter.startDocument();

				walker.traverseSubtree(contentNode);

				formatter.endDocument();
			}

			file << std::endl;

			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

}

namespace InputXSLT {

xercesc::DOMDocument* FunctionWriteFile::constructDocument(
	boost::filesystem::path filePath,
	xalan::XalanNode* const contentNode
) {
	xercesc::DOMDocument* const domDocument(
		xercesc::DOMImplementation::getImplementation()->createDocument(
			nullptr,
			*XercesStringGuard<XMLCh>("content"),
			nullptr
		)
	);

	xercesc::DOMNode* const rootNode(
		domDocument->getDocumentElement()
	);

	ResultNodeFacade result(domDocument, rootNode, "file");
	result.setAttribute("path", filePath.string());

	if ( contentNode != nullptr ) {
		if ( serializeNodeToFile(filePath, contentNode) ) {
			result.setAttribute("result", "success");
		} else {
			result.setAttribute("result", "error");
		}
	} else {
		result.setAttribute("result", "error");
	}

	return domDocument;
}

}