aboutsummaryrefslogtreecommitdiff
path: root/rss/xmlutilities.cpp
blob: 988a1f090fa8fae5696184d592a75b2087c954a6 (plain) (blame)
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
98
99
100
#include "xmlutilities.h"

#include <cstring>

namespace rsspp {

std::string get_content(xmlNode* node)
{
	std::string retval;
	if (node) {
		xmlChar* content = xmlNodeGetContent(node);
		if (content) {
			retval = reinterpret_cast<const char*>(content);
			xmlFree(content);
		}
	}
	return retval;
}

std::string get_xml_content(xmlNode* node, xmlDocPtr doc)
{
	xmlBufferPtr buf = xmlBufferCreate();
	std::string result;

	cleanup_namespaces(node);

	if (node->children) {
		for (xmlNodePtr ptr = node->children; ptr != nullptr;
			ptr = ptr->next) {
			if (xmlNodeDump(buf, doc, ptr, 0, 0) >= 0) {
				result.append(
					reinterpret_cast<const char*>(xmlBufferContent(buf)));
				xmlBufferEmpty(buf);
			} else {
				result.append(get_content(ptr));
			}
		}
	} else {
		result = get_content(node); // fallback
	}
	xmlBufferFree(buf);

	return result;
}

void cleanup_namespaces(xmlNodePtr node)
{
	node->ns = nullptr;
	for (auto ptr = node->children; ptr != nullptr; ptr = ptr->next) {
		cleanup_namespaces(ptr);
	}
}

std::string get_prop(xmlNode* node, const std::string& prop,
	const std::string& ns)
{
	std::string retval;
	if (node) {
		xmlChar* value = nullptr;
		if (ns.empty()) {
			value = xmlGetProp(node,
					reinterpret_cast<const xmlChar*>(prop.c_str()));
		} else {
			value = xmlGetNsProp(node,
					reinterpret_cast<const xmlChar*>(prop.c_str()),
					reinterpret_cast<const xmlChar*>(ns.c_str()));
		}
		if (value) {
			retval = reinterpret_cast<const char*>(value);
			xmlFree(value);
		}
	}
	return retval;
}

bool has_namespace(xmlNode* node, const char* ns_uri)
{
	if (!ns_uri && !node->ns) {
		return true;
	}
	if (ns_uri && node->ns && node->ns->href &&
		strcmp(reinterpret_cast<const char*>(node->ns->href), ns_uri) == 0) {
		return true;
	}
	return false;
}

bool node_is(xmlNode* node, const char* name, const char* ns_uri)
{
	if (!node || !name || !node->name) {
		return false;
	}

	if (strcmp(reinterpret_cast<const char*>(node->name), name) == 0) {
		return has_namespace(node, ns_uri);
	}
	return false;
}

} // namespace rsspp