MyGUI 3.5.3
MyGUI_XmlDocument.cpp
Go to the documentation of this file.
1/*
2 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
3 * Distributed under the MIT License
4 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
5 */
6
7#include "MyGUI_Precompiled.h"
8#include "MyGUI_XmlDocument.h"
9#include "MyGUI_DataManager.h"
10
11#include <pugixml.hpp>
12#include <fstream>
13#include <filesystem>
15
16namespace MyGUI::xml
17{
18
19 constexpr unsigned int ParseFlags = pugi::parse_default | pugi::parse_declaration | pugi::parse_comments;
20 constexpr unsigned int FormatFlags = pugi::format_write_bom | pugi::format_default;
21
22 Document::Document() :
23 mDoc(std::make_shared<pugi::xml_document>()),
24 mResult(std::make_shared<pugi::xml_parse_result>())
25 {
26 clearLastError();
27 }
28
29 bool Document::open(const std::string& _filename)
30 {
31 return open(MyGUI::utility::toPath(_filename));
32 }
33
34 bool Document::open(const std::filesystem::path& _filename)
35 {
36 clear();
37
38 *mResult = mDoc->load_file(_filename.c_str(), ParseFlags);
39
40 if (!*mResult)
41 mLastErrorFile = _filename;
42
43 return *mResult;
44 }
45
46 bool Document::open(std::istream& _stream)
47 {
48 clear();
49
50 *mResult = mDoc->load(_stream, ParseFlags);
51
52 if (!*mResult)
53 mLastErrorFromStream = true;
54
55 return *mResult;
56 }
57
58 bool Document::open(IDataStream* _stream)
59 {
60 clear();
61
62 const auto data = _stream->readAll();
63
64 *mResult = mDoc->load_buffer(data.data(), data.size(), ParseFlags);
65 if (!*mResult)
66 mLastErrorFromStream = true;
67
68 return *mResult;
69 }
70
71 bool Document::save(const std::string& _filename)
72 {
73 return save(MyGUI::utility::toPath(_filename));
74 }
75
76 bool Document::save(const std::filesystem::path& _filename)
77 {
78 clearLastError();
79 bool result = mDoc->save_file(_filename.c_str(), "\t", FormatFlags);
80
81 if (!result)
82 {
83 mLastError = "Failed to save XML file";
84 mLastErrorFromStream = false;
85 mLastErrorFile = _filename;
86 }
87 return result;
88 }
89
90 bool Document::save(std::ostream& _stream)
91 {
92 clearLastError();
93 mDoc->save(_stream, "\t", FormatFlags);
94 if (!_stream)
95 {
96 mLastError = "Failed to save XML stream";
97 mLastErrorFromStream = true;
98 }
99 return static_cast<bool>(_stream);
100 }
101
102 void Document::clear()
103 {
104 mDoc->reset();
105 clearLastError();
106 }
107
108 bool Document::open(const UString& _filename)
109 {
110 return open(_filename.asUTF8());
111 }
112
113 bool Document::save(const UString& _filename)
114 {
115 return save(_filename.asUTF8());
116 }
117
118 void Document::clearLastError()
119 {
120 *mResult = {};
121 mResult->status = pugi::status_ok;
122 mLastError.clear();
123 mLastErrorFile.clear();
124 mLastErrorFromStream = false;
125 }
126
127 ElementPtr Document::getRoot() const
128 {
129 return mDoc->document_element();
130 }
131
132 ElementPtr Document::createDeclaration(std::string_view _version, std::string_view _encoding)
133 {
134 // remove existing declaration
135 for (auto child = mDoc->first_child(); child;)
136 {
137 auto next = child.next_sibling();
138 if (child.type() == pugi::node_declaration)
139 mDoc->remove_child(child);
140 child = next;
141 }
142
143 auto decl = mDoc->prepend_child(pugi::node_declaration);
144 decl.set_name("xml");
145 decl.append_attribute("version") = _version;
146 decl.append_attribute("encoding") = _encoding;
147 return decl;
148 }
149
150 ElementPtr Document::createRoot(std::string_view _name)
151 {
152 // remove existing root elements
153 for (auto child = mDoc->first_child(); child;)
154 {
155 auto next = child.next_sibling();
156 if (child.type() == pugi::node_element)
157 mDoc->remove_child(child);
158 child = next;
159 }
160
161 return mDoc->append_child(_name);
162 }
163
164 std::string Document::getLastError() const
165 {
166 const std::string fileName = mLastErrorFromStream ? "<stream>" : MyGUI::utility::toUtf8(mLastErrorFile);
167 if (!*mResult)
168 {
169 size_t line = 0, col = 0;
170 std::string lineText;
171 if (mResult->offset >= 0 && !mLastErrorFile.empty())
172 {
173 std::ifstream file(mLastErrorFile, std::ios::binary);
174 if (file)
175 {
176 line = 1;
177 std::string data((std::istreambuf_iterator<char>(file)), {});
178 for (ptrdiff_t i = 0; i < mResult->offset && i < (ptrdiff_t)data.size(); ++i)
179 {
180 if (data[i] == '\n')
181 ++line;
182 }
183 ptrdiff_t start = mResult->offset;
184 while (start > 0 && data[start - 1] != '\n')
185 --start;
186 col = mResult->offset - start + 1;
187 ptrdiff_t end = data.size();
188 for (ptrdiff_t i = start; i < (ptrdiff_t)data.size(); ++i)
189 {
190 if (data[i] == '\n')
191 {
192 end = i;
193 break;
194 }
195 }
196 lineText = data.substr(start, end - start);
197 }
198 }
199 return utility::
200 toString("'", mResult->description(), "', ", fileName, "(", line, ",", col, "): ", lineText);
201 }
202 if (!mLastError.empty())
203 {
204 return utility::toString("'", mLastError, "', file='", fileName, "'");
205 }
206 return {};
207 }
208
209 ElementEnumerator::ElementEnumerator(std::shared_ptr<pugi::xml_node> parent)
210 {
211 for (auto child : parent->children())
212 mElements.emplace_back(child);
213 }
214
215 bool ElementEnumerator::next()
216 {
217 return ++mIndex < mElements.size();
218 }
219
220 bool ElementEnumerator::next(std::string_view _name)
221 {
222 while (next())
223 {
224 if (mElements[mIndex].getName() == _name)
225 return true;
226 }
227 return false;
228 }
229
230 ElementPtr ElementEnumerator::operator->() const
231 {
232 return mElements[mIndex];
233 }
234
235 ElementPtr ElementEnumerator::current()
236 {
237 return mElements[mIndex];
238 }
239
240 ElementPtr::ElementPtr(const pugi::xml_node& _node) :
241 mNode(_node ? std::make_shared<pugi::xml_node>(_node) : nullptr)
242 {
243 }
244
245 ElementPtr* ElementPtr::operator->()
246 {
247 return this;
248 }
249
250 const ElementPtr* ElementPtr::operator->() const
251 {
252 return this;
253 }
254
255 ElementPtr ElementPtr::createChild(std::string_view _name, std::string_view _content)
256 {
257 auto child = mNode->append_child(_name);
258 if (!_content.empty())
259 child.text().set(_content);
260 return ElementPtr(child);
261 }
262
263 void ElementPtr::removeChild(ElementPtr _child)
264 {
265 mNode->remove_child(*_child.mNode);
266 }
267
268 void ElementPtr::addAttribute(std::string_view _key, std::string_view _value)
269 {
270 mNode->append_attribute(_key) = _value;
271 }
272
273 void ElementPtr::removeAttribute(std::string_view _key)
274 {
275 mNode->remove_attribute(_key);
276 }
277
278 void ElementPtr::setAttribute(std::string_view _key, std::string_view _value)
279 {
280 auto attr = mNode->attribute(_key);
281 if (attr)
282 attr.set_value(_value);
283 else
284 mNode->append_attribute(_key) = _value;
285 }
286
287 void ElementPtr::setContent(std::string_view _content)
288 {
289 mNode->remove_children();
290 mNode->text().set(_content);
291 }
292
293 void ElementPtr::clear()
294 {
295 mNode->remove_children();
296 mNode->remove_attributes();
297 }
298
299 bool ElementPtr::findAttribute(std::string_view _name, std::string& _value)
300 {
301 auto attr = mNode->attribute(_name);
302 if (attr)
303 {
304 _value = attr.as_string();
305 return true;
306 }
307 return false;
308 }
309
310 std::string_view ElementPtr::findAttribute(std::string_view _name)
311 {
312 auto attr = mNode->attribute(_name);
313 if (attr)
314 return attr.as_string();
315 return {};
316 }
317
318 std::string ElementPtr::getName() const
319 {
320 return mNode->name();
321 }
322
323 std::string ElementPtr::getContent() const
324 {
325 return mNode->text().as_string();
326 }
327
328 VectorAttributes ElementPtr::getAttributes() const
329 {
330 VectorAttributes attrs;
331 for (auto attr : mNode->attributes())
332 attrs.emplace_back(attr.name(), attr.as_string());
333 return attrs;
334 }
335
336 ElementPtr ElementPtr::getParent() const
337 {
338 return ElementPtr(mNode->parent());
339 }
340
341 ElementEnumerator ElementPtr::getElementEnumerator()
342 {
343 return ElementEnumerator(mNode);
344 }
345
346 ElementPtr::operator pugi::xml_node() const
347 {
348 return *mNode;
349 }
350
351 const pugi::xml_node& ElementPtr::node() const
352 {
353 return *mNode;
354 }
355
356 Element::Element(std::shared_ptr<pugi::xml_node> _node, std::shared_ptr<pugi::xml_document> _doc) :
357 ElementPtr(*_node),
358 mDocument(std::move(_doc))
359 {
360 }
361
362 std::unique_ptr<Element> ElementPtr::createCopy()
363 {
364 auto doc = std::make_shared<pugi::xml_document>();
365 auto copy = doc->append_copy(*mNode);
366 auto nodeCopy = std::make_shared<pugi::xml_node>(copy);
367 return std::make_unique<Element>(nodeCopy, doc);
368 }
369
370} // namespace MyGUI
__attribute__((visibility("default"))) void trim(std std::string toString(T _value)
std::string toUtf8(const std::filesystem::path &path)
Convert a filesystem path to UTF-8 bytes.
std::filesystem::path toPath(std::string_view text)
Convert UTF-8 bytes to a native filesystem path.
constexpr unsigned int FormatFlags
std::vector< PairAttribute > VectorAttributes
constexpr unsigned int ParseFlags