Merge pull request #26166 from ksooo/improve-plugin-ctx-menus
[xbmc.git] / xbmc / utils / XSLTUtils.cpp
blobba069ba303bd43c78ea70bad1550aff4ad860fe2
1 /*
2 * Copyright (C) 2005-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
9 #include "XSLTUtils.h"
10 #include "log.h"
11 #include <libxslt/xslt.h>
12 #include <libxslt/transform.h>
14 #ifndef TARGET_WINDOWS
15 #include <iostream>
16 #endif
18 #define TMP_BUF_SIZE 512
19 void err(void *ctx, const char *msg, ...) {
20 char string[TMP_BUF_SIZE];
21 va_list arg_ptr;
22 va_start(arg_ptr, msg);
23 vsnprintf(string, TMP_BUF_SIZE, msg, arg_ptr);
24 va_end(arg_ptr);
25 CLog::Log(LOGDEBUG, "XSLT: {}", string);
28 XSLTUtils::XSLTUtils()
30 // initialize libxslt
31 xmlSubstituteEntitiesDefault(1);
32 xmlLoadExtDtdDefaultValue = 0;
33 xsltSetGenericErrorFunc(NULL, err);
36 XSLTUtils::~XSLTUtils()
38 if (m_xmlInput)
39 xmlFreeDoc(m_xmlInput);
40 if (m_xmlOutput)
41 xmlFreeDoc(m_xmlOutput);
42 if (m_xsltStylesheet)
43 xsltFreeStylesheet(m_xsltStylesheet);
46 bool XSLTUtils::XSLTTransform(std::string& output)
48 const char *params[16+1];
49 params[0] = NULL;
50 m_xmlOutput = xsltApplyStylesheet(m_xsltStylesheet, m_xmlInput, params);
51 if (!m_xmlOutput)
53 CLog::Log(LOGDEBUG, "XSLT: xslt transformation failed");
54 return false;
57 xmlChar *xmlResultBuffer = NULL;
58 int xmlResultLength = 0;
59 int res = xsltSaveResultToString(&xmlResultBuffer, &xmlResultLength, m_xmlOutput, m_xsltStylesheet);
60 if (res == -1)
62 xmlFree(xmlResultBuffer);
63 return false;
66 output.append((const char *)xmlResultBuffer, xmlResultLength);
67 xmlFree(xmlResultBuffer);
69 return true;
72 bool XSLTUtils::SetInput(const std::string& input)
74 m_xmlInput = xmlParseMemory(input.c_str(), input.size());
75 if (!m_xmlInput)
76 return false;
77 return true;
80 bool XSLTUtils::SetStylesheet(const std::string& stylesheet)
82 if (m_xsltStylesheet) {
83 xsltFreeStylesheet(m_xsltStylesheet);
84 m_xsltStylesheet = NULL;
87 m_xmlStylesheet = xmlParseMemory(stylesheet.c_str(), stylesheet.size());
88 if (!m_xmlStylesheet)
90 CLog::Log(LOGDEBUG, "could not xmlParseMemory stylesheetdoc");
91 return false;
94 m_xsltStylesheet = xsltParseStylesheetDoc(m_xmlStylesheet);
95 if (!m_xsltStylesheet) {
96 CLog::Log(LOGDEBUG, "could not parse stylesheetdoc");
97 xmlFree(m_xmlStylesheet);
98 m_xmlStylesheet = NULL;
99 return false;
102 return true;