2 #include <lib/base/eerror.h>
3 #include "xmlgenerator.h"
5 XmlGenerator::XmlGenerator(FILE *f) : m_file(f), m_indent(true), m_level(0)
7 ::fprintf(m_file, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
10 XmlGenerator::~XmlGenerator()
14 void XmlGenerator::vprint(const char *fmt, va_list ap, bool newline)
19 for (i = 0; i < m_level; i++)
20 ::fprintf(m_file, "\t");
22 ::vfprintf(m_file, fmt, ap);
25 ::fprintf(m_file, "\n");
28 void XmlGenerator::print(const char *fmt, ...)
33 vprint(fmt, ap, false);
37 void XmlGenerator::printLn(const char *fmt, ...)
42 vprint(fmt, ap, true);
46 void XmlGenerator::open(const std::string &tag, bool newline)
49 printLn("<%s>", tag.c_str());
51 print("<%s>", tag.c_str());
59 void XmlGenerator::open(const std::string &tag)
64 void XmlGenerator::close()
66 ASSERT(!m_tags.empty());
70 printLn("</%s>", m_tags.top().c_str());
76 void XmlGenerator::comment(const std::string &str)
78 printLn("<!-- %s -->", str.c_str());
81 void XmlGenerator::commentFromErrno(const std::string &tag)
84 comment(strerror(errno));
88 std::string XmlGenerator::cDataEscape(const std::string &str)
90 const std::string search = "]]>";
91 const std::string replace = "]]]]><![CDATA[>";
97 pos = str.find(search, opos);
98 if (pos == std::string::npos)
100 ret.append(str, opos, pos - opos);
102 pos += search.size();
105 ret.append(str, opos, std::string::npos);
109 void XmlGenerator::cDataFromCmd(const std::string &tag, const std::string &cmd)
111 FILE *pipe = ::popen(cmd.c_str(), "re");
114 commentFromErrno(tag);
119 char *lineptr = NULL;
123 ssize_t ret = ::getline(&lineptr, &n, pipe);
126 result.append(lineptr, ret);
133 cDataFromString(tag, result);
136 void XmlGenerator::cDataFromFile(const std::string &tag, const std::string &filename, const char *filter)
138 std::ifstream in(filename.c_str());
143 commentFromErrno(tag);
147 while (std::getline(in, line))
148 if (!filter || !line.find(filter))
149 content += line + '\n';
152 cDataFromString(tag, content);
155 void XmlGenerator::cDataFromString(const std::string &tag, const std::string &str)
160 printLn("<![CDATA[");
161 std::swap(m_indent, indent);
162 print("%s", cDataEscape(str).c_str());
164 std::swap(m_indent, indent);
168 void XmlGenerator::string(const std::string &tag, const std::string &str)
171 print("%s", str.c_str());
175 void XmlGenerator::stringFromFile(const std::string &tag, const std::string &filename)
177 std::ifstream in(filename.c_str());
181 commentFromErrno(tag);
185 std::getline(in, line);