xml_parser.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. /*************************************************************************/
  2. /* xml_parser.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "xml_parser.h"
  31. #include "core/print_string.h"
  32. //#define DEBUG_XML
  33. VARIANT_ENUM_CAST(XMLParser::NodeType);
  34. static bool _equalsn(const CharType *str1, const CharType *str2, int len) {
  35. int i;
  36. for (i = 0; i < len && str1[i] && str2[i]; ++i) {
  37. if (str1[i] != str2[i]) {
  38. return false;
  39. }
  40. }
  41. // if one (or both) of the strings was smaller then they
  42. // are only equal if they have the same length
  43. return (i == len) || (str1[i] == 0 && str2[i] == 0);
  44. }
  45. String XMLParser::_replace_special_characters(const String &origstr) {
  46. int pos = origstr.find("&");
  47. int oldPos = 0;
  48. if (pos == -1) {
  49. return origstr;
  50. }
  51. String newstr;
  52. while (pos != -1 && pos < origstr.length() - 2) {
  53. // check if it is one of the special characters
  54. int specialChar = -1;
  55. for (int i = 0; i < (int)special_characters.size(); ++i) {
  56. const CharType *p = &origstr[pos] + 1;
  57. if (_equalsn(&special_characters[i][1], p, special_characters[i].length() - 1)) {
  58. specialChar = i;
  59. break;
  60. }
  61. }
  62. if (specialChar != -1) {
  63. newstr += (origstr.substr(oldPos, pos - oldPos));
  64. newstr += (special_characters[specialChar][0]);
  65. pos += special_characters[specialChar].length();
  66. } else {
  67. newstr += (origstr.substr(oldPos, pos - oldPos + 1));
  68. pos += 1;
  69. }
  70. // find next &
  71. oldPos = pos;
  72. pos = origstr.find("&", pos);
  73. }
  74. if (oldPos < origstr.length() - 1) {
  75. newstr += (origstr.substr(oldPos, origstr.length() - oldPos));
  76. }
  77. return newstr;
  78. }
  79. static inline bool _is_white_space(char c) {
  80. return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
  81. }
  82. //! sets the state that text was found. Returns true if set should be set
  83. bool XMLParser::_set_text(char *start, char *end) {
  84. // check if text is more than 2 characters, and if not, check if there is
  85. // only white space, so that this text won't be reported
  86. if (end - start < 3) {
  87. char *p = start;
  88. for (; p != end; ++p) {
  89. if (!_is_white_space(*p)) {
  90. break;
  91. }
  92. }
  93. if (p == end) {
  94. return false;
  95. }
  96. }
  97. // set current text to the parsed text, and replace xml special characters
  98. String s = String::utf8(start, (int)(end - start));
  99. node_name = _replace_special_characters(s);
  100. // current XML node type is text
  101. node_type = NODE_TEXT;
  102. return true;
  103. }
  104. void XMLParser::_parse_closing_xml_element() {
  105. node_type = NODE_ELEMENT_END;
  106. node_empty = false;
  107. attributes.clear();
  108. ++P;
  109. const char *pBeginClose = P;
  110. while (*P && *P != '>') {
  111. ++P;
  112. }
  113. node_name = String::utf8(pBeginClose, (int)(P - pBeginClose));
  114. #ifdef DEBUG_XML
  115. print_line("XML CLOSE: " + node_name);
  116. #endif
  117. if (*P) {
  118. ++P;
  119. }
  120. }
  121. void XMLParser::_ignore_definition() {
  122. node_type = NODE_UNKNOWN;
  123. char *F = P;
  124. // move until end marked with '>' reached
  125. while (*P && *P != '>') {
  126. ++P;
  127. }
  128. node_name.parse_utf8(F, P - F);
  129. if (*P) {
  130. ++P;
  131. }
  132. }
  133. bool XMLParser::_parse_cdata() {
  134. if (*(P + 1) != '[') {
  135. return false;
  136. }
  137. node_type = NODE_CDATA;
  138. // skip '<![CDATA['
  139. int count = 0;
  140. while (*P && count < 8) {
  141. ++P;
  142. ++count;
  143. }
  144. if (!*P) {
  145. node_name = "";
  146. return true;
  147. }
  148. char *cDataBegin = P;
  149. char *cDataEnd = nullptr;
  150. // find end of CDATA
  151. while (*P && !cDataEnd) {
  152. if (*P == '>' &&
  153. (*(P - 1) == ']') &&
  154. (*(P - 2) == ']')) {
  155. cDataEnd = P - 2;
  156. }
  157. ++P;
  158. }
  159. if (cDataEnd) {
  160. cDataEnd = P;
  161. }
  162. node_name = String::utf8(cDataBegin, (int)(cDataEnd - cDataBegin));
  163. #ifdef DEBUG_XML
  164. print_line("XML CDATA: " + node_name);
  165. #endif
  166. return true;
  167. }
  168. void XMLParser::_parse_comment() {
  169. node_type = NODE_COMMENT;
  170. P += 1;
  171. char *pEndOfInput = data + length;
  172. char *pCommentBegin;
  173. char *pCommentEnd;
  174. if (P + 1 < pEndOfInput && P[0] == '-' && P[1] == '-') {
  175. // Comment, use '-->' as end.
  176. pCommentBegin = P + 2;
  177. for (pCommentEnd = pCommentBegin; pCommentEnd + 2 < pEndOfInput; pCommentEnd++) {
  178. if (pCommentEnd[0] == '-' && pCommentEnd[1] == '-' && pCommentEnd[2] == '>') {
  179. break;
  180. }
  181. }
  182. if (pCommentEnd + 2 < pEndOfInput) {
  183. P = pCommentEnd + 3;
  184. } else {
  185. P = pCommentEnd = pEndOfInput;
  186. }
  187. } else {
  188. // Like document type definition, match angle brackets.
  189. pCommentBegin = P;
  190. int count = 1;
  191. while (*P && count) {
  192. if (*P == '>') {
  193. --count;
  194. } else if (*P == '<') {
  195. ++count;
  196. }
  197. ++P;
  198. }
  199. if (count) {
  200. pCommentEnd = P;
  201. } else {
  202. pCommentEnd = P - 1;
  203. }
  204. }
  205. node_name = String::utf8(pCommentBegin, (int)(pCommentEnd - pCommentBegin));
  206. #ifdef DEBUG_XML
  207. print_line("XML COMMENT: " + node_name);
  208. #endif
  209. }
  210. void XMLParser::_parse_opening_xml_element() {
  211. node_type = NODE_ELEMENT;
  212. node_empty = false;
  213. attributes.clear();
  214. // find name
  215. const char *startName = P;
  216. // find end of element
  217. while (*P && *P != '>' && !_is_white_space(*P)) {
  218. ++P;
  219. }
  220. const char *endName = P;
  221. // find attributes
  222. while (*P && *P != '>') {
  223. if (_is_white_space(*P)) {
  224. ++P;
  225. } else {
  226. if (*P != '/') {
  227. // we've got an attribute
  228. // read the attribute names
  229. const char *attributeNameBegin = P;
  230. while (*P && !_is_white_space(*P) && *P != '=') {
  231. ++P;
  232. }
  233. if (!*P) {
  234. break;
  235. }
  236. const char *attributeNameEnd = P;
  237. ++P;
  238. // read the attribute value
  239. // check for quotes and single quotes, thx to murphy
  240. while ((*P != '\"') && (*P != '\'') && *P) {
  241. ++P;
  242. }
  243. if (!*P) { // malformatted xml file
  244. break;
  245. }
  246. const char attributeQuoteChar = *P;
  247. ++P;
  248. const char *attributeValueBegin = P;
  249. while (*P != attributeQuoteChar && *P) {
  250. ++P;
  251. }
  252. const char *attributeValueEnd = P;
  253. if (*P) {
  254. ++P;
  255. }
  256. Attribute attr;
  257. attr.name = String::utf8(attributeNameBegin,
  258. (int)(attributeNameEnd - attributeNameBegin));
  259. String s = String::utf8(attributeValueBegin,
  260. (int)(attributeValueEnd - attributeValueBegin));
  261. attr.value = _replace_special_characters(s);
  262. attributes.push_back(attr);
  263. } else {
  264. // tag is closed directly
  265. ++P;
  266. node_empty = true;
  267. break;
  268. }
  269. }
  270. }
  271. // check if this tag is closing directly
  272. if (endName > startName && *(endName - 1) == '/') {
  273. // directly closing tag
  274. node_empty = true;
  275. endName--;
  276. }
  277. node_name = String::utf8(startName, (int)(endName - startName));
  278. #ifdef DEBUG_XML
  279. print_line("XML OPEN: " + node_name);
  280. #endif
  281. if (*P) {
  282. ++P;
  283. }
  284. }
  285. void XMLParser::_parse_current_node() {
  286. char *start = P;
  287. node_offset = P - data;
  288. // more forward until '<' found
  289. while (*P != '<' && *P) {
  290. ++P;
  291. }
  292. if (P - start > 0) {
  293. // we found some text, store it
  294. if (_set_text(start, P)) {
  295. return;
  296. }
  297. }
  298. if (!*P) {
  299. return;
  300. }
  301. ++P;
  302. // based on current token, parse and report next element
  303. switch (*P) {
  304. case '/':
  305. _parse_closing_xml_element();
  306. break;
  307. case '?':
  308. _ignore_definition();
  309. break;
  310. case '!':
  311. if (!_parse_cdata()) {
  312. _parse_comment();
  313. }
  314. break;
  315. default:
  316. _parse_opening_xml_element();
  317. break;
  318. }
  319. }
  320. uint64_t XMLParser::get_node_offset() const {
  321. return node_offset;
  322. };
  323. Error XMLParser::seek(uint64_t p_pos) {
  324. ERR_FAIL_COND_V(!data, ERR_FILE_EOF);
  325. ERR_FAIL_COND_V(p_pos >= length, ERR_FILE_EOF);
  326. P = data + p_pos;
  327. return read();
  328. };
  329. void XMLParser::_bind_methods() {
  330. ClassDB::bind_method(D_METHOD("read"), &XMLParser::read);
  331. ClassDB::bind_method(D_METHOD("get_node_type"), &XMLParser::get_node_type);
  332. ClassDB::bind_method(D_METHOD("get_node_name"), &XMLParser::get_node_name);
  333. ClassDB::bind_method(D_METHOD("get_node_data"), &XMLParser::get_node_data);
  334. ClassDB::bind_method(D_METHOD("get_node_offset"), &XMLParser::get_node_offset);
  335. ClassDB::bind_method(D_METHOD("get_attribute_count"), &XMLParser::get_attribute_count);
  336. ClassDB::bind_method(D_METHOD("get_attribute_name", "idx"), &XMLParser::get_attribute_name);
  337. ClassDB::bind_method(D_METHOD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value);
  338. ClassDB::bind_method(D_METHOD("has_attribute", "name"), &XMLParser::has_attribute);
  339. ClassDB::bind_method(D_METHOD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value);
  340. ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe);
  341. ClassDB::bind_method(D_METHOD("is_empty"), &XMLParser::is_empty);
  342. ClassDB::bind_method(D_METHOD("get_current_line"), &XMLParser::get_current_line);
  343. ClassDB::bind_method(D_METHOD("skip_section"), &XMLParser::skip_section);
  344. ClassDB::bind_method(D_METHOD("seek", "position"), &XMLParser::seek);
  345. ClassDB::bind_method(D_METHOD("open", "file"), &XMLParser::open);
  346. ClassDB::bind_method(D_METHOD("open_buffer", "buffer"), &XMLParser::open_buffer);
  347. BIND_ENUM_CONSTANT(NODE_NONE);
  348. BIND_ENUM_CONSTANT(NODE_ELEMENT);
  349. BIND_ENUM_CONSTANT(NODE_ELEMENT_END);
  350. BIND_ENUM_CONSTANT(NODE_TEXT);
  351. BIND_ENUM_CONSTANT(NODE_COMMENT);
  352. BIND_ENUM_CONSTANT(NODE_CDATA);
  353. BIND_ENUM_CONSTANT(NODE_UNKNOWN);
  354. };
  355. Error XMLParser::read() {
  356. // if not end reached, parse the node
  357. if (P && (P - data) < (int64_t)length - 1 && *P != 0) {
  358. _parse_current_node();
  359. return OK;
  360. }
  361. return ERR_FILE_EOF;
  362. }
  363. XMLParser::NodeType XMLParser::get_node_type() {
  364. return node_type;
  365. }
  366. String XMLParser::get_node_data() const {
  367. ERR_FAIL_COND_V(node_type != NODE_TEXT, "");
  368. return node_name;
  369. }
  370. String XMLParser::get_node_name() const {
  371. ERR_FAIL_COND_V(node_type == NODE_TEXT, "");
  372. return node_name;
  373. }
  374. int XMLParser::get_attribute_count() const {
  375. return attributes.size();
  376. }
  377. String XMLParser::get_attribute_name(int p_idx) const {
  378. ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
  379. return attributes[p_idx].name;
  380. }
  381. String XMLParser::get_attribute_value(int p_idx) const {
  382. ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
  383. return attributes[p_idx].value;
  384. }
  385. bool XMLParser::has_attribute(const String &p_name) const {
  386. for (int i = 0; i < attributes.size(); i++) {
  387. if (attributes[i].name == p_name) {
  388. return true;
  389. }
  390. }
  391. return false;
  392. }
  393. String XMLParser::get_attribute_value(const String &p_name) const {
  394. int idx = -1;
  395. for (int i = 0; i < attributes.size(); i++) {
  396. if (attributes[i].name == p_name) {
  397. idx = i;
  398. break;
  399. }
  400. }
  401. ERR_FAIL_COND_V_MSG(idx < 0, "", "Attribute not found: " + p_name + ".");
  402. return attributes[idx].value;
  403. }
  404. String XMLParser::get_attribute_value_safe(const String &p_name) const {
  405. int idx = -1;
  406. for (int i = 0; i < attributes.size(); i++) {
  407. if (attributes[i].name == p_name) {
  408. idx = i;
  409. break;
  410. }
  411. }
  412. if (idx < 0) {
  413. return "";
  414. }
  415. return attributes[idx].value;
  416. }
  417. bool XMLParser::is_empty() const {
  418. return node_empty;
  419. }
  420. Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) {
  421. ERR_FAIL_COND_V(p_buffer.size() == 0, ERR_INVALID_DATA);
  422. if (data) {
  423. memdelete_arr(data);
  424. }
  425. length = p_buffer.size();
  426. data = memnew_arr(char, length + 1);
  427. memcpy(data, p_buffer.ptr(), length);
  428. data[length] = 0;
  429. P = data;
  430. return OK;
  431. }
  432. Error XMLParser::open(const String &p_path) {
  433. Error err;
  434. FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err);
  435. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'.");
  436. length = file->get_len();
  437. ERR_FAIL_COND_V(length < 1, ERR_FILE_CORRUPT);
  438. if (data) {
  439. memdelete_arr(data);
  440. }
  441. data = memnew_arr(char, length + 1);
  442. file->get_buffer((uint8_t *)data, length);
  443. data[length] = 0;
  444. P = data;
  445. memdelete(file);
  446. return OK;
  447. }
  448. void XMLParser::skip_section() {
  449. // skip if this element is empty anyway.
  450. if (is_empty()) {
  451. return;
  452. }
  453. // read until we've reached the last element in this section
  454. int tagcount = 1;
  455. while (tagcount && read() == OK) {
  456. if (get_node_type() == XMLParser::NODE_ELEMENT &&
  457. !is_empty()) {
  458. ++tagcount;
  459. } else if (get_node_type() == XMLParser::NODE_ELEMENT_END) {
  460. --tagcount;
  461. }
  462. }
  463. }
  464. void XMLParser::close() {
  465. if (data) {
  466. memdelete_arr(data);
  467. }
  468. data = nullptr;
  469. length = 0;
  470. P = nullptr;
  471. node_empty = false;
  472. node_type = NODE_NONE;
  473. node_offset = 0;
  474. }
  475. int XMLParser::get_current_line() const {
  476. return 0;
  477. }
  478. XMLParser::XMLParser() {
  479. data = nullptr;
  480. close();
  481. special_characters.push_back("&amp;");
  482. special_characters.push_back("<lt;");
  483. special_characters.push_back(">gt;");
  484. special_characters.push_back("\"quot;");
  485. special_characters.push_back("'apos;");
  486. }
  487. XMLParser::~XMLParser() {
  488. if (data) {
  489. memdelete_arr(data);
  490. }
  491. }