XMLFile.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "ArrayPtr.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "Serializer.h"
  29. #include "XMLFile.h"
  30. #include <pugixml.hpp>
  31. #include "DebugNew.h"
  32. namespace Urho3D
  33. {
  34. /// XML writer for pugixml.
  35. class XMLWriter : public pugi::xml_writer
  36. {
  37. public:
  38. /// Construct.
  39. XMLWriter(Serializer& dest) :
  40. dest_(dest),
  41. success_(true)
  42. {
  43. }
  44. /// Write bytes to output.
  45. void write(const void* data, size_t size)
  46. {
  47. if (dest_.Write(data, size) != size)
  48. success_ = false;
  49. }
  50. /// Destination serializer.
  51. Serializer& dest_;
  52. /// Success flag.
  53. bool success_;
  54. };
  55. XMLFile::XMLFile(Context* context) :
  56. Resource(context),
  57. document_(new pugi::xml_document())
  58. {
  59. }
  60. XMLFile::~XMLFile()
  61. {
  62. delete document_;
  63. document_ = 0;
  64. }
  65. void XMLFile::RegisterObject(Context* context)
  66. {
  67. context->RegisterFactory<XMLFile>();
  68. }
  69. bool XMLFile::Load(Deserializer& source)
  70. {
  71. PROFILE(LoadXMLFile);
  72. unsigned dataSize = source.GetSize();
  73. if (!dataSize && !source.GetName().Empty())
  74. {
  75. LOGERROR("Zero sized XML data in " + source.GetName());
  76. return false;
  77. }
  78. SharedArrayPtr<char> buffer(new char[dataSize]);
  79. if (source.Read(buffer.Get(), dataSize) != dataSize)
  80. return false;
  81. if (!document_->load_buffer(buffer.Get(), dataSize))
  82. {
  83. LOGERROR("Could not parse XML data from " + source.GetName());
  84. return false;
  85. }
  86. // Note: this probably does not reflect internal data structure size accurately
  87. SetMemoryUse(dataSize);
  88. return true;
  89. }
  90. bool XMLFile::Save(Serializer& dest) const
  91. {
  92. XMLWriter writer(dest);
  93. document_->save(writer);
  94. return writer.success_;
  95. }
  96. XMLElement XMLFile::CreateRoot(const String& name)
  97. {
  98. document_->reset();
  99. pugi::xml_node root = document_->append_child(name.CString());
  100. return XMLElement(this, root.internal_object());
  101. }
  102. XMLElement XMLFile::GetRoot(const String& name)
  103. {
  104. pugi::xml_node root = document_->first_child();
  105. if (root.empty())
  106. return XMLElement();
  107. if (!name.Empty() && name != root.name())
  108. return XMLElement();
  109. else
  110. return XMLElement(this, root.internal_object());
  111. }
  112. void XMLFile::Patch(XMLFile* patchFile)
  113. {
  114. pugi::xml_node root = patchFile->document_->first_child();
  115. for (pugi::xml_node::iterator patch = root.begin(); patch != root.end(); patch++)
  116. {
  117. pugi::xml_attribute sel = patch->attribute("sel");
  118. if (sel.empty())
  119. {
  120. LOGERROR("XML Patch failed due to node not having a sel attribute.");
  121. continue;
  122. }
  123. // Only select a single node at a time, they can use xpath to select specific ones in multiple otherwise the node set becomes invalid due to changes.
  124. pugi::xpath_node original = document_->select_single_node(sel.value());
  125. if (!original)
  126. {
  127. LOGERRORF("XML Patch failed with bad select: %s.", sel.value());
  128. continue;
  129. }
  130. if (strcmp(patch->name(),"add") == 0)
  131. PatchAdd(*patch, original);
  132. else if (strcmp(patch->name(), "replace") == 0)
  133. PatchReplace(*patch, original);
  134. else if (strcmp(patch->name(), "remove") == 0)
  135. PatchRemove(original);
  136. else
  137. LOGERROR("XMLFiles used for patching should only use 'add', 'replace' or 'remove' elements.");
  138. }
  139. }
  140. void XMLFile::PatchAdd(const pugi::xml_node& patch, pugi::xpath_node& original)
  141. {
  142. // If not a node, log an error.
  143. if (original.attribute())
  144. {
  145. LOGERRORF("XML Patch failed calling Add due to not selecting a node, %s attribute was selected.", original.attribute().name());
  146. return;
  147. }
  148. // If no type add node, if contains '@' treat as attribute.
  149. pugi::xml_attribute type = patch.attribute("type");
  150. if (!type || strlen(type.value()) <= 0)
  151. AddNode(patch, original);
  152. else if (type.value()[0] == '@')
  153. AddAttribute(patch, original);
  154. }
  155. void XMLFile::PatchReplace(const pugi::xml_node& patch, pugi::xpath_node& original)
  156. {
  157. // If no attribute but node then its a node, otherwise its an attribute or null.
  158. if (!original.attribute() && original.node())
  159. {
  160. pugi::xml_node parent = original.node().parent();
  161. parent.insert_copy_before(patch.first_child(), original.node());
  162. parent.remove_child(original.node());
  163. }
  164. else if (original.attribute())
  165. {
  166. original.attribute().set_value(patch.child_value());
  167. }
  168. }
  169. void XMLFile::PatchRemove(const pugi::xpath_node& original)
  170. {
  171. // If no attribute but node then its a node, otherwise its an attribute or null.
  172. if (!original.attribute() && original.node())
  173. {
  174. pugi::xml_node parent = original.parent();
  175. parent.remove_child(original.node());
  176. }
  177. else if (original.attribute())
  178. {
  179. pugi::xml_node parent = original.parent();
  180. parent.remove_attribute(original.attribute());
  181. }
  182. }
  183. void XMLFile::AddNode(const pugi::xml_node& patch, pugi::xpath_node& original)
  184. {
  185. // If pos is null, append or prepend add as a child, otherwise add before or after, the default is to append as a child.
  186. pugi::xml_attribute pos = patch.attribute("pos");
  187. if (!pos || strlen(pos.value()) <= 0 || pos.value() == "append")
  188. {
  189. pugi::xml_node::iterator start = patch.begin();
  190. pugi::xml_node::iterator end = patch.end();
  191. // There can not be two consecutive text nodes, so check to see if they need to be combined.
  192. // If they have been we can skip the first node of the nodes to add.
  193. if (CombineText(patch.first_child(), original.node().last_child(), false))
  194. start++;
  195. for (; start != end; start++)
  196. original.node().append_copy(*start);
  197. }
  198. else if (strcmp(pos.value(), "prepend") == 0)
  199. {
  200. pugi::xml_node::iterator start = patch.begin();
  201. pugi::xml_node::iterator end = patch.end();
  202. // There can not be two consecutive text nodes, so check to see if they need to be combined.
  203. // If they have been we can skip the last node of the nodes to add.
  204. if (CombineText(patch.last_child(), original.node().first_child(), true))
  205. end--;
  206. pugi::xml_node pos = original.node().first_child();
  207. for (; start != end; start++)
  208. original.node().insert_copy_before(*start, pos);
  209. }
  210. else if (strcmp(pos.value(), "before") == 0)
  211. {
  212. pugi::xml_node::iterator start = patch.begin();
  213. pugi::xml_node::iterator end = patch.end();
  214. // There can not be two consecutive text nodes, so check to see if they need to be combined.
  215. // If they have been we can skip the first node of the nodes to add.
  216. if (CombineText(patch.first_child(), original.node().previous_sibling(), false))
  217. start++;
  218. // There can not be two consecutive text nodes, so check to see if they need to be combined.
  219. // If they have been we can skip the last node of the nodes to add.
  220. if (CombineText(patch.last_child(), original.node(), true))
  221. end--;
  222. for (; start != end; start++)
  223. original.parent().insert_copy_before(*start, original.node());
  224. }
  225. else if (strcmp(pos.value(), "after") == 0)
  226. {
  227. pugi::xml_node::iterator start = patch.begin();
  228. pugi::xml_node::iterator end = patch.end();
  229. // There can not be two consecutive text nodes, so check to see if they need to be combined.
  230. // If they have been we can skip the first node of the nodes to add.
  231. if (CombineText(patch.first_child(), original.node(), false))
  232. start++;
  233. // There can not be two consecutive text nodes, so check to see if they need to be combined.
  234. // If they have been we can skip the last node of the nodes to add.
  235. if (CombineText(patch.last_child(), original.node().next_sibling(), true))
  236. end--;
  237. pugi::xml_node pos = original.node();
  238. for (; start != end; start++)
  239. pos = original.parent().insert_copy_after(*start, pos);
  240. }
  241. }
  242. void XMLFile::AddAttribute(const pugi::xml_node& patch, pugi::xpath_node& original)
  243. {
  244. pugi::xml_attribute attribute = patch.attribute("type");
  245. if (!patch.first_child() && patch.first_child().type() != pugi::node_pcdata)
  246. {
  247. LOGERRORF("XML Patch failed calling Add due to attempting to add non text to an attribute for %s.", attribute.value());
  248. return;
  249. }
  250. String name(attribute.value());
  251. name = name.Substring(1);
  252. pugi::xml_attribute newAttribute = original.node().append_attribute(name.CString());
  253. newAttribute.set_value(patch.child_value());
  254. }
  255. bool XMLFile::CombineText(const pugi::xml_node& patch, pugi::xml_node original, bool prepend)
  256. {
  257. if (!patch || !original)
  258. return false;
  259. if ((patch.type() == pugi::node_pcdata && original.type() == pugi::node_pcdata) ||
  260. (patch.type() == pugi::node_cdata && original.type() == pugi::node_cdata))
  261. {
  262. if (prepend)
  263. original.set_value(ToString("%s%s", patch.value(), original.value()).CString());
  264. else
  265. original.set_value(ToString("%s%s", original.value(), patch.value()).CString());
  266. return true;
  267. }
  268. return false;
  269. }
  270. }