载入中...
搜索中...
未找到
Xml.cpp
浏览该文件的文档.
1#include "common/Xml.h"
3
4#include <cctype>
5#include <cstdlib>
6#include <functional>
7#include <utility>
8
9namespace eve::xml {
10
11struct Node {
12 std::string tag;
13 std::unordered_map<std::string, std::string> attributes;
14 std::vector<std::unique_ptr<Node>> children;
15 Node* parent = nullptr;
16};
17
18namespace {
19
20class Parser {
21public:
22 explicit Parser(const std::string& text) : s_(text) {}
23
24 bool parse(std::unique_ptr<Node>& out, std::string* error) {
25 skipMisc();
26 if (!parseElement(out, nullptr, 0)) {
27 if (error && error->empty())
28 *error = "invalid XML near offset " + std::to_string(pos_);
29 return false;
30 }
31 skipMisc();
32 if (pos_ != s_.size()) {
33 if (error) *error = "trailing data at offset " + std::to_string(pos_);
34 return false;
35 }
36 return true;
37 }
38
39private:
40 static constexpr size_t kMaxDepth = 256;
41 const std::string& s_;
42 size_t pos_ = 0;
43
44 void skipWs() {
45 while (pos_ < s_.size() &&
46 (s_[pos_] == ' ' || s_[pos_] == '\t' || s_[pos_] == '\n' || s_[pos_] == '\r'))
47 ++pos_;
48 }
49
50 bool startsWith(const char* lit) const {
51 const size_t n = std::char_traits<char>::length(lit);
52 return pos_ + n <= s_.size() && s_.compare(pos_, n, lit) == 0;
53 }
54
55 bool skipComment() {
56 if (!startsWith("<!--")) return false;
57 pos_ += 4;
58 while (pos_ + 2 < s_.size()) {
59 if (s_[pos_] == '-' && s_[pos_ + 1] == '-' && s_[pos_ + 2] == '>') {
60 pos_ += 3;
61 return true;
62 }
63 ++pos_;
64 }
65 return false;
66 }
67
68 bool skipProcessingInstruction() {
69 if (!startsWith("<?")) return false;
70 pos_ += 2;
71 while (pos_ + 1 < s_.size()) {
72 if (s_[pos_] == '?' && s_[pos_ + 1] == '>') {
73 pos_ += 2;
74 return true;
75 }
76 ++pos_;
77 }
78 return false;
79 }
80
81 bool skipDoctype() {
82 if (!startsWith("<!DOCTYPE") && !startsWith("<!doctype")) return false;
83 pos_ += 9;
84 int depth = 1;
85 while (pos_ < s_.size() && depth > 0) {
86 if (s_[pos_] == '<')
87 ++depth;
88 else if (s_[pos_] == '>')
89 --depth;
90 ++pos_;
91 }
92 return depth == 0;
93 }
94
95 void skipMisc() {
96 for (;;) {
97 skipWs();
98 if (skipComment() || skipProcessingInstruction() || skipDoctype()) continue;
99 break;
100 }
101 }
102
103 bool parseName(std::string& out) {
104 if (pos_ >= s_.size()) return false;
105 const unsigned char c0 = static_cast<unsigned char>(s_[pos_]);
106 if (!(std::isalpha(c0) || c0 == '_' || c0 == ':')) return false;
107 const size_t start = pos_++;
108 while (pos_ < s_.size()) {
109 const unsigned char c = static_cast<unsigned char>(s_[pos_]);
110 if (std::isalnum(c) || c == '_' || c == '-' || c == '.' || c == ':')
111 ++pos_;
112 else
113 break;
114 }
115 out = s_.substr(start, pos_ - start);
116 return !out.empty();
117 }
118
119 bool decodeEntity(std::string& out) {
120 if (pos_ >= s_.size() || s_[pos_] != '&') return false;
121 ++pos_;
122 if (startsWith("amp;")) {
123 pos_ += 4;
124 out += '&';
125 return true;
126 }
127 if (startsWith("lt;")) {
128 pos_ += 3;
129 out += '<';
130 return true;
131 }
132 if (startsWith("gt;")) {
133 pos_ += 3;
134 out += '>';
135 return true;
136 }
137 if (startsWith("quot;")) {
138 pos_ += 5;
139 out += '"';
140 return true;
141 }
142 if (startsWith("apos;")) {
143 pos_ += 5;
144 out += '\'';
145 return true;
146 }
147 if (pos_ < s_.size() && s_[pos_] == '#') {
148 ++pos_;
149 unsigned long code = 0;
150 if (pos_ < s_.size() && (s_[pos_] == 'x' || s_[pos_] == 'X')) {
151 ++pos_;
152 const size_t start = pos_;
153 while (pos_ < s_.size() && std::isxdigit(static_cast<unsigned char>(s_[pos_]))) ++pos_;
154 if (pos_ == start || pos_ >= s_.size() || s_[pos_] != ';') return false;
155 code = std::strtoul(s_.substr(start, pos_ - start).c_str(), nullptr, 16);
156 } else {
157 const size_t start = pos_;
158 while (pos_ < s_.size() && std::isdigit(static_cast<unsigned char>(s_[pos_]))) ++pos_;
159 if (pos_ == start || pos_ >= s_.size() || s_[pos_] != ';') return false;
160 code = std::strtoul(s_.substr(start, pos_ - start).c_str(), nullptr, 10);
161 }
162 ++pos_; // ';'
163 if (code == 0 || code > 0x10FFFFul) return false;
164 if (code < 0x80) {
165 out += static_cast<char>(code);
166 } else if (code < 0x800) {
167 out += static_cast<char>(0xC0 | (code >> 6));
168 out += static_cast<char>(0x80 | (code & 0x3F));
169 } else if (code < 0x10000) {
170 out += static_cast<char>(0xE0 | (code >> 12));
171 out += static_cast<char>(0x80 | ((code >> 6) & 0x3F));
172 out += static_cast<char>(0x80 | (code & 0x3F));
173 } else {
174 out += static_cast<char>(0xF0 | (code >> 18));
175 out += static_cast<char>(0x80 | ((code >> 12) & 0x3F));
176 out += static_cast<char>(0x80 | ((code >> 6) & 0x3F));
177 out += static_cast<char>(0x80 | (code & 0x3F));
178 }
179 return true;
180 }
181 return false;
182 }
183
184 bool parseAttributeValue(std::string& out) {
185 if (pos_ >= s_.size()) return false;
186 const char quote = s_[pos_];
187 if (quote != '"' && quote != '\'') return false;
188 ++pos_;
189 out.clear();
190 while (pos_ < s_.size()) {
191 const char c = s_[pos_];
192 if (c == quote) {
193 ++pos_;
194 return true;
195 }
196 if (c == '&') {
197 if (!decodeEntity(out)) return false;
198 continue;
199 }
200 if (c == '<') return false;
201 out += c;
202 ++pos_;
203 }
204 return false;
205 }
206
207 bool parseAttributes(Node& node) {
208 for (;;) {
209 skipWs();
210 if (pos_ >= s_.size()) return false;
211 if (s_[pos_] == '/' || s_[pos_] == '>') return true;
212 std::string name;
213 if (!parseName(name)) return false;
214 skipWs();
215 if (pos_ >= s_.size() || s_[pos_] != '=') return false;
216 ++pos_;
217 skipWs();
218 std::string value;
219 if (!parseAttributeValue(value)) return false;
220 node.attributes[std::move(name)] = std::move(value);
221 }
222 }
223
224 bool skipTextUntilTag() {
225 while (pos_ < s_.size() && s_[pos_] != '<') {
226 if (s_[pos_] == '&') {
227 std::string discard;
228 if (!decodeEntity(discard)) return false;
229 } else {
230 ++pos_;
231 }
232 }
233 return true;
234 }
235
236 bool parseElement(std::unique_ptr<Node>& out, Node* parent, size_t depth) {
237 if (depth > kMaxDepth) return false;
238 skipMisc();
239 if (pos_ >= s_.size() || s_[pos_] != '<') return false;
240 if (startsWith("</") || startsWith("<?") || startsWith("<!")) return false;
241 ++pos_;
242 auto node = std::make_unique<Node>();
243 node->parent = parent;
244 if (!parseName(node->tag)) return false;
245 if (!parseAttributes(*node)) return false;
246 skipWs();
247 if (pos_ >= s_.size()) return false;
248 if (s_[pos_] == '/') {
249 ++pos_;
250 if (pos_ >= s_.size() || s_[pos_] != '>') return false;
251 ++pos_;
252 out = std::move(node);
253 return true;
254 }
255 if (s_[pos_] != '>') return false;
256 ++pos_;
257
258 for (;;) {
259 if (!skipTextUntilTag()) return false;
260 if (pos_ >= s_.size() || s_[pos_] != '<') return false;
261 if (startsWith("</")) {
262 pos_ += 2;
263 std::string endTag;
264 if (!parseName(endTag)) return false;
265 skipWs();
266 if (pos_ >= s_.size() || s_[pos_] != '>') return false;
267 ++pos_;
268 if (endTag != node->tag) return false;
269 out = std::move(node);
270 return true;
271 }
272 if (startsWith("<!--")) {
273 if (!skipComment()) return false;
274 continue;
275 }
276 if (startsWith("<?")) {
277 if (!skipProcessingInstruction()) return false;
278 continue;
279 }
280 if (startsWith("<![CDATA[")) {
281 pos_ += 9;
282 while (pos_ + 2 < s_.size()) {
283 if (s_[pos_] == ']' && s_[pos_ + 1] == ']' && s_[pos_ + 2] == '>') {
284 pos_ += 3;
285 break;
286 }
287 ++pos_;
288 }
289 continue;
290 }
291 std::unique_ptr<Node> child;
292 if (!parseElement(child, node.get(), depth + 1)) return false;
293 node->children.push_back(std::move(child));
294 }
295 }
296};
297
298} // namespace
299
300Document::Document() = default;
301Document::~Document() = default;
302Document::Document(Document&&) noexcept = default;
303Document& Document::operator=(Document&&) noexcept = default;
304
305Document Document::parse(const std::string& text, std::string* error) {
306 Document doc;
307 if (error) error->clear();
308 Parser parser(text);
309 if (!parser.parse(doc.root_, error)) {
310 doc.root_.reset();
311 return doc;
312 }
313 return doc;
314}
315
316std::string Element::tagName() const { return node_ ? node_->tag : std::string{}; }
317
319 return node_ && node_->parent ? Element(node_->parent) : Element();
320}
321
322bool Element::hasAttribute(const char* name) const {
323 return node_ && name && node_->attributes.find(name) != node_->attributes.end();
324}
325
326std::string Element::getAttribute(const char* name, const std::string& fallback) const {
327 if (!node_ || !name) return fallback;
328 const auto it = node_->attributes.find(name);
329 return it == node_->attributes.end() ? fallback : it->second;
330}
331
332int Element::getIntAttribute(const char* name, int fallback) const {
333 if (!hasAttribute(name)) return fallback;
334 try {
335 return std::stoi(getAttribute(name));
336 } catch (...) {
337 return fallback;
338 }
339}
340
341std::vector<Element> Element::children(const char* tag) const {
342 std::vector<Element> out;
343 if (!node_) return out;
344 for (const auto& child : node_->children) {
345 if (!tag || child->tag == tag) out.emplace_back(Element(child.get()));
346 }
347 return out;
348}
349
350std::vector<Element> Element::elementsByTag(const char* tag) const {
351 std::vector<Element> out;
352 if (!node_ || !tag) return out;
353 std::function<void(const Node*)> walk = [&](const Node* node) {
354 for (const auto& child : node->children) {
355 if (child->tag == tag) out.emplace_back(Element(child.get()));
356 walk(child.get());
357 }
358 };
359 walk(node_);
360 return out;
361}
362
363} // namespace eve::xml
Duration start
std::string name
Definition ECS.cpp:154
DiagnosticCode code
glm::vec3 n
Definition Grass.cpp:63
std::int32_t c
const ColourScope * parent
char quote
const std::string * tag
std::string error
Definition Package.cpp:174
Object::Ptr value
const RoadNode * node
std::string text
ScriptStructure out
Share string attribute map operations through the Windows Foundation DLL.
std::uint32_t depth
bool hasAttribute(const char *name) const
Definition Xml.cpp:322
std::vector< Element > children(const char *tag=nullptr) const
Definition Xml.cpp:341
Element parent() const
Definition Xml.cpp:318
std::string tagName() const
Definition Xml.cpp:316
std::string getAttribute(const char *name, const std::string &fallback={}) const
Definition Xml.cpp:326
int getIntAttribute(const char *name, int fallback=0) const
Definition Xml.cpp:332
std::vector< Element > elementsByTag(const char *tag) const
Definition Xml.cpp:350
std::string tag
Definition Xml.cpp:12
std::unordered_map< std::string, std::string > attributes
Definition Xml.cpp:13
std::vector< std::unique_ptr< Node > > children
Definition Xml.cpp:14
Node * parent
Definition Xml.cpp:15