summaryrefslogtreecommitdiff
path: root/src/xml_test.cpp
blob: 0b978a9565d53c6aedb78bf2c23225e37ae17eec (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
#include <iostream>
#include <string>
#include <tuple>
using namespace std;

#include "xml.hpp"

class MyXML : public XML {
public:
	explicit MyXML(ostream& out, size_t indent = 4)
	    : pout_(&out)
	    , indent_(indent)
	{
	}

protected:
	void handle_start(string_view name, const vector<tuple<string_view, string_view>>& attr) override
	{
		*pout_ << string(depth_++ * indent_, ' ')
		       << "<" << name;

		auto start = cbegin(attr);
		auto end   = cend(attr);
		if ( start != end ) {
			*pout_ << " " << get<0>(*start) << "=\"" << get<1>(*start) << "\"";

			++start; // skip first Element
			for ( ; start != end; ++start ) {
				*pout_ << ",  " << get<0>(*start) << "=\"" << get<1>(*start) << "\"";
			}
		}

		*pout_ << ">" << '\n';
	}

	void handle_end(string_view name) override
	{
		*pout_ << string(--depth_ * indent_, ' ')
		       << "</" << name << ">"
		       << '\n';
	}
	void handle_cdata_start() override
	{
		*pout_ << string(depth_ * indent_, ' ')
		       << "<![CDATA[" << '\n';
	}

	void handle_cdata_end() override
	{
		*pout_ << string(depth_ * indent_, ' ')
		       << "]]>" << '\n';
	}

	static bool contains_only_whitespace(span<const char> data)
	{
		return ranges::all_of(data, [](unsigned char chr) {
			return std::isspace(chr);
		});
	}

	void handle_character_data(span<const char> data) override
	{
		if ( contains_only_whitespace(data) ) {
			return;
		}

		*pout_ << string(depth_ * indent_, ' ') << "Data: ";
		pout_->write(data.data(), static_cast<streamsize>(data.size()));
		*pout_ << '\n';
	}

private:
	ostream* pout_;
	size_t   depth_{};
	size_t   indent_;
};

int
main()
{
	try {
		MyXML myxml(cout);
		myxml.parse(cin);
	}
	catch ( exception& e ) {
		cerr << "Fehler: " << e.what() << '\n';
	}
}