MezzanineEngine 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
xml.h
1 // © Copyright 2010 - 2014 BlackTopp Studios Inc.
2 /* This file is part of The Mezzanine Engine.
3 
4  The Mezzanine Engine is free software: you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation, either version 3 of the License, or
7  (at your option) any later version.
8 
9  The Mezzanine Engine is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with The Mezzanine Engine. If not, see <http://www.gnu.org/licenses/>.
16 */
17 /* The original authors have included a copy of the license specified above in the
18  'Docs' folder. See 'gpl.txt'
19 */
20 /* We welcome the use of the Mezzanine engine to anyone, including companies who wish to
21  Build professional software and charge for their product.
22 
23  However there are some practical restrictions, so if your project involves
24  any of the following you should contact us and we will try to work something
25  out:
26  - DRM or Copy Protection of any kind(except Copyrights)
27  - Software Patents You Do Not Wish to Freely License
28  - Any Kind of Linking to Non-GPL licensed Works
29  - Are Currently In Violation of Another Copyright Holder's GPL License
30  - If You want to change our code and not add a few hundred MB of stuff to
31  your distribution
32 
33  These and other limitations could cause serious legal problems if you ignore
34  them, so it is best to simply contact us or the Free Software Foundation, if
35  you have any questions.
36 
37  Joseph Toppi - toppij@gmail.com
38  John Blackwood - makoenergy02@gmail.com
39 */
40 /*
41  * pugixml parser - version 1.2
42  * --------------------------------------------------------
43  * Copyright © 2006-2012, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
44  * Report bugs and download new versions at http://pugixml.org/
45  *
46  * This library is distributed under the MIT License. See notice at the end
47  * of this file.
48  *
49  * This work is based on the pugxml parser, which is:
50  * Copyright © 2003, by Kristen Wegner (kristen@tima.net)
51  */
52 #ifndef _XML_H
53 #define _XML_H
54 
55 #ifndef XML_VERSION
56 // Define version macro; evaluates to major * 100 + minor so that it's safe to use in less-than comparisons
57 /// @def XML_VERSION This correlates to the version of pugixml this uses
58 /// @brief
59 # define XML_VERSION 100
60 #endif
61 
62 #include "swig.h"
63 #ifdef SWIG_XML
64  #ifdef SWIG_UNSAFE
65  %module MezzanineXML
66  #else
67  #define SWIG_SAFE
68  %module MezzanineXMLSafe
69  #endif
70  #define SWIG_MODULE_SET
71 #endif
72 
73 #include "XML/objectrange.h"
74 #include "XML/attribute.h"
75 #include "XML/attributeiterator.h"
76 #include "XML/document.h"
77 #include "XML/memorymanagement.h"
78 #include "XML/nodeiterator.h"
79 #include "XML/nodetext.h"
80 #include "XML/node.h"
81 #include "XML/parseresult.h"
82 #include "XML/treewalker.h"
83 #include "XML/writer.h"
84 #include "XML/xmlenumerations.h"
85 #include "XML/xmlstring.h"
86 #include "XML/xpathnode.h"
87 #include "XML/xpathnodeset.h"
88 #include "XML/xpathparseresult.h"
89 #include "XML/xpathvariable.h"
90 #include "XML/xpathvariableset.h"
91 #include "XML/xpathquery.h"
92 
93 
94 namespace Mezzanine
95 {
96  /// @brief All tools for working with XML are located in this namespace
97  /// @details The contents of this namespace has many details covered in the @ref XMLManual
98  namespace XML
99  {}
100 }
101 
102 /// @page XMLManual Mezzanine::xml Manual
103 /// This will describe how to use the XML components of the Mezzanine
104 /// @section XMLTOC Table Of Contents
105 /// - @ref XMLOverview
106 /// - @ref XMLIntroduction
107 /// - @ref XMLFeedBack
108 /// - @ref XMLAcknowledgments
109 /// - @ref XMLLicense
110 /// - @ref XMLDOM
111 /// - @ref XMLTreeStructure
112 /// - @ref XMLInterface
113 /// - @ref XMLThreadSafety
114 /// - @ref XMLExceptionSafety
115 /// - @ref XMLMemory
116 /// - @ref XMLCustomAlloc
117 /// - @ref XMLMemoryInternals
118 /// - @ref XMLLoading
119 /// - @ref XMLLoadingFiles
120 /// - @ref XMLLoadingFromMemory
121 /// - @ref XMLLoadingStreams
122 /// - @ref XMLLoadingErrors
123 /// - @ref XMLLoadingParsingOptions
124 /// - @ref XMLLoadingEncodings
125 /// - @ref XMLLoadingStandards
126 /// - @ref XMLAccessing
127 /// - @ref XMLAccessingBasics
128 /// - @ref XMLAccessingNodeData
129 /// - @ref XMLAccessingAttributeData
130 /// - @ref XMLAccessingContentBased
131 /// - @ref XMLAccessingIterators
132 /// - @ref XMLAccessingWalker
133 /// - @ref XMLAccessingPredicates
134 /// - @ref XMLAccessingMisc
135 /// - @ref XMLModifying
136 /// - @ref XMLModifyingNodeData
137 /// - @ref XMLModifyingAttributeData
138 /// - @ref XMLModifyingAdding
139 /// - @ref XMLModifyingRemoving
140 /// - @ref XMLModifyingCloning
141 /// - @ref XMLSaving
142 /// - @ref XMLSavingFile
143 /// - @ref XMLSavingStreams
144 /// - @ref XMLSavingWriter
145 /// - @ref XMLSavingSubtree
146 /// - @ref XMLSavingOptions
147 /// - @ref XMLSavingEncodings
148 /// - @ref XMLXPath
149 /// - @ref XMLXPathTypes
150 /// - @ref XMLXPathSelecting
151 /// - @ref XMLXPathQuery
152 /// - @ref XMLXPathVariables
153 /// - @ref XMLXPathError
154 /// - @ref XMLXPathStandards
155 ///
156 /// \n \n
157 /// @section XMLOverview Overview
158 /// - @ref XMLIntroduction
159 /// - @ref XMLFeedBack
160 /// - @ref XMLAcknowledgments
161 /// - @ref XMLLicense
162 ///
163 /// @subsection XMLIntroduction Introduction
164 /// Mezzanine::xml is a light-weight C++ XML processing library. It consists of a DOM-like interface with rich traversal/modification capabilities, an
165 /// extremely fast XML parser which constructs the DOM tree from an XML file/buffer, and an @ref Mezzanine::XML::XPathQuery "XPath 1.0 implementation"
166 /// for complex data-driven tree queries. Unicode is fully support via UF8 in 8bit characters and for
167 /// conversions between different Unicode encodings (which happen automatically during parsing/saving).
168 /// \n \n
169 /// Mezzanine::xml enables very fast, convenient and memory-efficient XML document processing. However, since Mezzanine::xml has a DOM parser, it can't process
170 /// XML documents that do not fit in memory; also the parser is a non-validating one, so if you need DTD or XML Schema validation, the XML parser
171 /// is not for you.
172 /// \n \n
173 /// @subsection XMLFeedBack FeedBack
174 /// If you believe you've found a bug in Mezzanine::xml (bugs include compilation problems (errors/warnings), crashes, performance degradation and incorrect
175 /// behavior), please contact Blacktopp Studios Inc ( http://www.blacktoppstudios.com/ ) . We check the the Forums ( http://www.blacktoppstudios.com/?page_id=753 )
176 /// and items sent by our contact form ( http://www.blacktoppstudios.com/?page_id=33 ) regularly. Be sure to include the relevant information so that
177 /// the bug can be reproduced: the version of Mezzanine::xml, compiler version and target architecture, the code that uses Mezzanine::xml and exhibits the bug, etc.
178 /// \n \n
179 /// Feature requests can be reported the same way as bugs, so if you're missing some functionality in Mezzanine::xml or if the API is rough in some places
180 /// and you can suggest an improvement, please let us know. However, please note that there are many factors when considering API changes (compatibility
181 /// with previous versions, API redundancy, etc.).
182 /// \n \n
183 /// If you have a contribution to Mezzanine::xml, such as build script for some build system/IDE, or a well-designed set of helper functions, or a binding
184 /// to some language other than C++, please let us know. You can include the relevant patches as issue attachments. We will have to communicate on the
185 /// Licensing terms of your contribution though.
186 /// \n \n
187 /// If the provided methods of contact have an issue or not possible due to privacy or other concerns, you can contact the Mezzanine::xml author ( toppij@blacktoppstudios.com )
188 /// or pugixml author ( arseny.kapoulkine@gmail.com ) by e-mail directly. If you have an issue that pertains to pugixml and not Mezzanine::xml you can visit the
189 /// pugixml issue submission form ( http:// ©ode.google.com/p/pugixml/issues/entry ) of the pugixml feature request form
190 /// ( http:// ©ode.google.com/p/pugixml/issues/entry?template=Feature%20request ).
191 /// \n \n
192 /// @subsection XMLAcknowledgments Acknowledgments
193 /// Mezzanine::xml and pugixml could not be developed without the help from many people; some of them are listed in this section. If you've played a part in
194 /// Mezzanine::xml or pugixml development and you can not find yourself on this list, I'm truly sorry; please send me an e-mail ( toppij@blacktoppstudios.com )
195 /// so I can fix this.
196 /// \n \n
197 /// Thanks to \b Arseny \b Kapoulkine for pugixml parser, which was used as a basis for Mezzanine::xml.
198 /// \n \n
199 /// Thanks to \b Kristen \b Wegner for pugxml parser, which was used as a basis for pugixml.
200 /// \n \n
201 /// Thanks to \b Neville \b Franks for contributions to pugxml parser.
202 /// \n \n
203 /// Thanks to \b Artyom \b Palvelev for suggesting a lazy gap contraction approach.
204 /// \n \n
205 /// Thanks to \b Vyacheslav \b Egorov for documentation proofreading.
206 /// \n \n
207 /// @subsection XMLLicense License
208 /// With written permission as per @ref OriginalpugixmlLicense "The original pugixml license" we he sublicensed Mezzanine::xml under the @ref GPLLicense "GPL Version 3". In short
209 /// This allows you to use Mezzanine::xml however you like with a few restrictions. If you change Mezzanine::xml you need to make the changes publically available.
210 /// If you make software using Mezzanine::xml you need to make the source code publicly available. You may not use and Digital Rights Management (DRM) software
211 /// to limit how others use the combined work you make. You can sell resulting works, but not through a digital distribution store that uses DRM.
212 ///
213 /// \n \n
214 /// @section XMLDOM Document Object Model
215 /// Mezzanine::xml stores XML data in DOM-like way: the entire XML document (both document structure and element data) is stored in memory as a tree. The tree can be
216 /// loaded from a character stream (file, string, C++ I/O stream), then traversed with the special API or XPath expressions. The whole tree is mutable: both node
217 /// structure and node/attribute data can be changed at any time. Finally, the result of document transformations can be saved to a character stream (file, C++
218 /// I/O stream or custom transport).
219 /// - @ref XMLTreeStructure
220 /// - @ref XMLInterface
221 /// - @ref XMLThreadSafety
222 /// - @ref XMLExceptionSafety
223 /// - @ref XMLMemory
224 /// - @ref XMLCustomAlloc
225 /// - @ref XMLMemoryInternals
226 ///
227 /// @subsection XMLTreeStructure Tree structure
228 /// The XML document is represented with a tree data structure. The root of the tree is the document itself, which corresponds to C++ type Mezzanine::XML::Document.
229 /// A Document has one or more child nodes, which correspond to C++ type Mezzanine::XML::Node. Nodes have different types; depending on a type, a node can have a
230 /// collection of child nodes, a collection of attributes, which correspond to C++ type Mezzanine::XML::Attribute, and some additional data (i.e. Name).
231 /// \n \n
232 /// The tree nodes can be of one of the following types (which together form the enumeration Mezzanine::XML::NodeType):
233 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeDocument Document node" - This is the root of the tree, which consists of several child nodes. This node corresponds
234 /// to Mezzanine::XML::Document class; note that Mezzanine::XML::Document is a sub-class of Mezzanine::XML::Node, so the entire node interface is also available. However,
235 /// document nodes are special in several ways, which are covered below. There can be only one document node in the tree; document node does not have any XML
236 /// representation. \n
237 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeElement Element/tag node" - This is the most common type of node, which represents XML elements. Element nodes
238 /// have a name, a collection of attributes and a collection of child nodes (both of which may be empty). The attribute is a simple name/value pair. The example
239 /// XML representation of element nodes is as follows:
240 /// @code{.xml}
241 /// <node attr="value"><child/></node>
242 /// @endcode
243 /// There are two element nodes here: one has name "node", single attribute "attr" and the single child "child" which has the name "child" and does not have
244 /// any attributes or child nodes. \n
245 /// - @ref Mezzanine::XML::NodeType "NodeType::NodePcdata Plain character data node" - Represent plain text in XML. PCDATA nodes have a value, but do not have a name
246 /// or children/attributes. Note that plain character data is not a part of the element node but instead has its own node; for example, an element node can have
247 /// several child PCDATA nodes. The example XML representation of text nodes is as follows:
248 /// @code
249 /// <node> text1 <child/> text2 </node>
250 /// @endcode
251 /// Here "node" element has three children, two of which are PCDATA nodes with values "text1" and "text2". \n
252 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeCdata Character data nodes" - These represent text in XML that is quoted in a special way. CDATA nodes do not differ
253 /// from PCDATA nodes except in XML representation - the above text example looks like this with CDATA:
254 /// @code
255 /// <node> <![CDATA[[text1]]> <child/> <![CDATA[[text2]]> </node>
256 /// @endcode
257 /// CDATA nodes make it easy to include non-escaped <, \& and > characters in plain text. CDATA value can not contain the character sequence ]]>, since it is
258 /// used to determine the end of node contents. \n
259 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeComment Comment nodes" - represent comments in XML. Comment nodes have a value, but do not have a name or
260 /// children/attributes. The example XML representation of a comment node is as follows:
261 /// @code
262 /// <!-- comment text -->
263 /// @endcode
264 /// Here the comment node has value "comment text". By default comment nodes are treated as non-essential part of XML markup and are not loaded during XML parsing.
265 /// You can override this behavior with Mezzanine::XML::ParseComments flag. \n
266 /// - @ref Mezzanine::XML::NodeType "NodeType::NodePi Processing instruction node" - Represent Processing Instructions (PI) in XML. PI nodes have a name and an optional
267 /// value, but do not have children/attributes. The example XML representation of a PI node is as follows:
268 /// @code
269 /// <?name value?>
270 /// @endcode
271 /// Here the name (also called PI target) is "name", and the value is "value". By default PI nodes are treated as non-essential part of XML markup and are not
272 /// loaded during XML parsing. You can override this behavior with Mezzanine::XML::ParsePi flag. \n
273 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeDeclaration Declaration node" - Represents document declarations in XML. Declaration nodes have a name ("xml") and an
274 /// optional collection of attributes, but do not have value or children. There can be only one declaration node in a document; moreover, it should be the topmost
275 /// node (its parent should be the document). The example XML representation of a declaration node is as follows:
276 /// @code
277 /// <?xml version="1.0"?>
278 /// @endcode
279 /// Here the node has name "xml" and a single attribute with name "version" and value "1.0". By default declaration nodes are treated as non-essential part of XML
280 /// markup and are not loaded during XML parsing. You can override this behavior with Mezzanine::XML::ParseDeclaration flag. Also, by default a dummy declaration is
281 /// output when XML document is saved unless there is already a declaration in the document; you can disable this with Mezzanine::XML::FormatNoDeclaration flag. \n
282 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeDocType Document type declaration node" - Represents document type declarations in XML. Document type declaration nodes
283 /// have a value, which corresponds to the entire document type contents; no additional nodes are created for inner elements like <!ENTITY>. There can be only one
284 /// document type declaration node in a document; moreover, it should be the topmost node (its parent should be the document). The example XML representation of a
285 /// document type declaration node is as follows:
286 /// @code
287 /// <!DOCTYPE greeting [ <!ELEMENT greeting (#PCDATA)> ]>
288 /// @endcode
289 /// Here the node has value "greeting [ <!ELEMENT greeting (#PCDATA)> ]". By default document type declaration nodes are treated as non-essential part of XML markup
290 /// and are not loaded during XML parsing. You can override this behavior with Mezzanine::XML::ParseDocType flag. \n
291 /// \n \n
292 /// Finally, here is a complete example of XML document and the corresponding tree representation:
293 /// @code
294 /// <?xml version="1.0"?>
295 /// <mesh name="mesh_root">
296 /// <!-- here is a mesh node -->
297 /// some text
298 /// <![CDATA[someothertext]]>
299 /// some more text
300 /// <node attr1="value1" attr2="value2" />
301 /// <node attr1="value2">
302 /// <innernode/>
303 /// </node>
304 /// </mesh>
305 /// <?include somedata?>
306 /// @endcode
307 /// @image html SampleTree.jpg "Complete Tree Representation of the Sample"
308 /// @image latex SampleTree.jpg "Complete Tree Representation of the Sample"
309 /// @image rtf SampleTree.jpg "Complete Tree Representation of the Sample"
310 /// @subsection XMLInterface C++ interface
311 /// Despite the fact that there are several node types, there are only three C++ classes representing the tree (Mezzanine::XML::Document, Mezzanine::XML::Node, Mezzanine::XML::Attribute);
312 /// some operations on Mezzanine::XML::Node are only valid for certain node types. The classes are described below.
313 /// \n \n
314 /// Mezzanine::XML::Document is the owner of the entire document structure; it is a non-copyable class. The interface of Mezzanine::XML::Document consists of loading functions
315 /// ( see @ref XMLLoading ), saving functions ( see @ref XMLSaving ) and the entire interface of Mezzanine::XML::Node, which allows for document inspection and/or modification.
316 /// Note that while Mezzanine::XML::Document is a sub-class of Mezzanine::XML::Node, Mezzanine::XML::Node is not a polymorphic type; the inheritance is present only to simplify usage.
317 /// Alternatively you can use the Mezzanine::XML::Document::DocumentElement function to get the element node that's the immediate child of the document.
318 /// \n \n
319 /// Default constructor of Mezzanine::XML::Document initializes the document to the tree with only a root node ( Mezzanine::XML::Document node). You can then populate it with data
320 /// using either tree modification functions or loading functions; all loading functions destroy the previous tree with all occupied memory, which puts existing
321 /// node/attribute handles for this document to invalid state. If you want to destroy the previous tree, you can use the Mezzanine::XML::Document::Reset function; it destroys
322 /// the tree and replaces it with either an empty one or a copy of the specified document. Destructor of Mezzanine::XML::Document also destroys the tree, thus the lifetime of
323 /// the document object should exceed the lifetimes of any node/attribute handles that point to the tree.
324 /// @warning While technically node/attribute handles can be alive when the tree they're referring to is destroyed, calling any member function for these handles results
325 /// in undefined behavior. Thus it is recommended to make sure that the document is destroyed only after all references to its nodes/attributes are destroyed.
326 ///
327 /// Mezzanine::XML::Node is the handle to a document node; it can point to any node in the document, including the document node itself. There is a common interface for nodes
328 /// of all types; the actual node type can be queried via the Mezzanine::XML::Node::Type() method. Note that Mezzanine::XML::Node is only a handle to the actual node, not the node
329 /// itself - you can have several Mezzanine::XML::node handles pointing to the same underlying object. Destroying Mezzanine::XML::Node handle does not destroy the node and does not
330 /// remove it from the tree. The size of Mezzanine::XML::Node is equal to that of a pointer, so it is nothing more than a lightweight wrapper around a pointer; you can safely
331 /// pass or return Mezzanine::xml:Node objects by value without additional overhead.
332 /// \n \n
333 /// There is a special value of Mezzanine::XML::Node type, known as null node or empty node (such nodes have type NodeNull). It does not correspond to any node in any document,
334 /// and thus resembles null pointer. However, all operations are defined on empty nodes; generally the operations don't do anything and return empty nodes/attributes or
335 /// empty strings as their result (see documentation for specific functions for more detailed information). This is useful for chaining calls; i.e. you can get the
336 /// grandparent of a node like so: node.GetParent().GetParent(); if a node is a null node or it does not have a parent, the first Node::GetParent() call returns null node;
337 /// the second GetParent() call then also returns null node, which can make error handling easier.
338 /// \n \n
339 /// Mezzanine::XML::Attribute is a handle to an XML attribute; it has the same semantics as Mezzanine::XML::Node, i.e. there can be several Mezzanine::XML::Attribute handles pointing to
340 /// the same underlying object and there is a special null attribute value, which propagates to function results.
341 /// \n \n
342 /// Both Mezzanine::XML::Node and Mezzanine::XML::Attribute have the default constructor which initializes them to null objects.
343 /// \n \n
344 /// Mezzanine::XML::Node and Mezzanine::XML::Attribute try to behave like pointers, that is, they can be compared with other objects of the same type, making it possible to use them
345 /// as keys in associative containers. All handles to the same underlying object are equal, and any two handles to different underlying objects are not equal. Null handles
346 /// only compare as equal to themselves. The result of relational comparison can not be reliably determined from the order of nodes in file or in any other way. Do not use
347 /// relational comparison operators except for search optimization (i.e. associative container keys).
348 /// \n \n
349 /// If you want to use Mezzanine::XML::Node or Mezzanine::XML::Attribute objects as keys in hash-based associative containers, you can use the Mezzanine::XML::Node::HashValue or
350 /// Mezzanine::XML::Attribute::HashValue member functions. They return the hash values that are guaranteed to be the same for all handles to the same underlying object. The hash
351 /// value for null handles is 0.
352 /// \n \n
353 /// Finally handles can be implicitly cast to boolean-like objects, so that you can test if the node/attribute is empty with the following code: if (node) { ... } or if
354 /// (!node) { ... } else { ... }. Alternatively you can check if a given Node/Attribute handle is null by calling the Mezzanine::XML::Attribute::Empty or the
355 /// Mezzanine::XML::Node::Empty Methods.
356 /// \n \n
357 /// Nodes and attributes do not exist without a document tree, so you can't create them without adding them to some document. Once underlying node/attribute objects are
358 /// destroyed, the handles to those objects become invalid. While this means that destruction of the entire tree invalidates all node/attribute handles, it also means that
359 /// destroying a subtree ( by calling Mezzanine::XML::Node::RemoveChild ) or removing an attribute invalidates the corresponding handles. There is no way to check handle
360 /// validity; you have to ensure correctness through external mechanisms.
361 /// \n \n
362 /// @subsection XMLThreadSafety Thread-safety guarantees
363 ///Almost all functions in Mezzanine::xml have the following thread-safety guarantees:
364 /// - It is safe to call free (non-member) functions from multiple threads
365 /// - It is safe to perform concurrent read-only accesses to the same tree (all constant member functions do not modify the tree)
366 /// - It is safe to perform concurrent read/write accesses, if there is only one read or write access to the single tree at a time
367 ///
368 /// Concurrent modification and traversing of a single tree requires synchronization, for example via reader-writer lock. Modification includes altering document structure
369 /// and altering individual node/attribute data, i.e. changing names/values.
370 /// \n \n
371 /// The only exception is Mezzanine::XML::SetMemory_management_functions; it modifies global variables and as such is not thread-safe. Its usage policy has more restrictions, see
372 /// @ref XMLCustomAlloc .
373 /// \n \n
374 /// @subsection XMLExceptionSafety Exception guarantees
375 /// With the exception of XPath, Mezzanine::xml itself does not throw any exceptions. Additionally, most Mezzanine::xml functions have a no-throw exception guarantee.
376 /// \n \n
377 /// This is not applicable to functions that operate on STL strings or IOstreams; such functions have either strong guarantee (functions that operate on strings) or basic
378 /// guarantee (functions that operate on streams). Also functions that call user-defined callbacks (i.e. Mezzanine::XML::Node::Traverse or Mezzanine::XML::Node::FindNode) do not
379 /// provide any exception guarantees beyond the ones provided by the callback.
380 /// \n \n
381 /// XPath functions may throw Mezzanine::XML::XPathException on parsing errors; also, XPath functions may
382 /// throw std::bad_alloc in low memory conditions. Still, XPath functions provide strong exception guarantee.
383 /// \n \n
384 /// @subsection XMLMemory Memory management
385 /// Mezzanine::xml requests the memory needed for document storage in big chunks, and allocates document data inside those chunks. This section discusses replacing functions
386 /// used for chunk allocation and internal memory management implementation.
387 /// \n \n
388 /// @warning The Mezzanine::xml memory system is pending tighter integration with memory management from the rest of the system. The functions and features described here should be
389 /// considered deprecated and internal to the engine. It is highly likely they will be replaced without warning by a global system to allocate memory in a more efficient way.
390 ///
391 /// \n \n
392 /// @subsubsection XMLCustomAlloc Custom memory allocation/deallocation functions
393 /// All memory for tree structure, tree data and XPath objects is allocated via globally specified functions, which default to malloc/free. You can set your own allocation
394 /// functions with Mezzanine::XML::SetMemory_management_functions function. The function interfaces are the same as that of malloc/free:
395 /// @code
396 /// typedef void* (*AllocationFunction)(size_t size);
397 /// typedef void (*deAllocationFunction)(void* ptr);
398 /// @endcode
399 /// You can use the following accessor functions to change or get current memory management functions:
400 /// @code
401 /// void Mezzanine::XML::SetMemory_management_functions(AllocationFunction allocate, deAllocationFunction deallocate);
402 /// AllocationFunction GetMemoryAllocationFunctionn();
403 /// deAllocationFunction GetMemoryDeallocationFunction();
404 /// @endcode
405 /// Allocation function is called with the size (in bytes) as an argument and should return a pointer to a memory block with alignment that is suitable for storage of primitive
406 /// types (usually a maximum of void* and double types alignment is sufficient) and size that is greater than or equal to the requested one. If the allocation fails, the function
407 /// has to return null pointer (throwing an exception from allocation function results in undefined behavior).
408 /// \n \n
409 /// Deallocation function is called with the pointer that was returned by some call to allocation function; it is never called with a null pointer. If memory management functions
410 /// are not thread-safe, library thread safety is not guaranteed.
411 /// \n \n
412 /// When setting new memory management functions, care must be taken to make sure that there are no live Mezzanine::xml objects. Otherwise when the objects are destroyed, the new
413 /// deallocation function will be called with the memory obtained by the old allocation function, resulting in undefined behavior.
414 /// \n \n
415 /// @subsubsection XMLMemoryInternals Document memory management internals
416 /// Constructing a document object using the default constructor does not result in any allocations; document node is stored inside the Mezzanine::XML::Document object
417 /// \n \n
418 /// When the document is loaded from file/buffer, unless an inplace loading function is used ( see @ref XMLLoadingFromMemory ), a complete copy of character stream is made; all
419 /// names/values of nodes and attributes are allocated in this buffer. This buffer is allocated via a single large allocation and is only freed when document memory is reclaimed
420 /// (i.e. if the Mezzanine::XML::Document object is destroyed or if another document is loaded in the same object). Also when loading from file or stream, an additional large allocation
421 /// may be performed if encoding conversion is required; a temporary buffer is allocated, and it is freed before load function returns.
422 /// \n \n
423 /// All additional memory, such as memory for document structure (node/attribute objects) and memory for node/attribute names/values is allocated in pages on the order of 32
424 /// kilobytes; actual objects are allocated inside the pages using a memory management scheme optimized for fast allocation/deallocation of many small objects. Because of the
425 /// scheme specifics, the pages are only destroyed if all objects inside them are destroyed; also, generally destroying an object does not mean that subsequent object creation
426 /// will reuse the same memory. This means that it is possible to devise a usage scheme which will lead to higher memory usage than expected; one example is adding a lot of nodes,
427 /// and them removing all even numbered ones; not a single page is reclaimed in the process. However this is an example specifically crafted to produce unsatisfying behavior;
428 /// in all practical usage scenarios the memory consumption is less than that of a general-purpose allocator because allocation meta-data is very small in size.
429 /// \n \n
430 /// @section XMLLoading Loading Documents
431 /// - @ref XMLLoadingFiles
432 /// - @ref XMLLoadingFromMemory
433 /// - @ref XMLLoadingStreams
434 /// - @ref XMLLoadingErrors
435 /// - @ref XMLLoadingParsingOptions
436 /// - @ref XMLLoadingEncodings
437 /// - @ref XMLLoadingStandards
438 ///
439 /// Mezzanine::xml provides several functions for loading XML data from various places - files, C++ iostreams, memory buffers. All functions use an extremely fast non-validating parser.
440 /// This parser is not fully W3C conformant - it can load any valid XML document, but does not perform some well-formedness checks. While considerable effort is made to reject
441 /// invalid XML documents, some validation is not performed for performance reasons. Also some XML transformations (i.e. EOL handling or attribute value normalization) can impact
442 /// parsing speed and thus can be disabled. However for vast majority of XML documents there is no performance difference between different parsing options. Parsing options also
443 /// control whether certain XML nodes are parsed; see @ref XMLLoadingParsingOptions for more information.
444 /// \n \n
445 /// XML data is always converted to internal character format before parsing. Mezzanine::xml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little
446 /// endian), UTF-32 (big and little endian); UCS-2 is naturally supported since it's a strict subset of UTF-16) and handles all encoding conversions automatically. Unless explicit
447 /// encoding is specified, loading functions perform automatic encoding detection based on first few characters of XML data, so in almost all cases you do not have to specify
448 /// document encoding. Encoding conversion is described in more detail in @ref XMLLoadingEncodings.
449 /// \n \n
450 /// @subsection XMLLoadingFiles Loading Document from a File
451 /// The most common source of XML data is files; Mezzanine::xml provides dedicated functions for loading an XML document from file:
452 /// @code
453 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::LoadFile(const char* path, unsigned int options = ParseDefault, Mezzanine::XML::Encoding DocumentEncoding = EncodingAuto);
454 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::LoadFile(const wchar_t* path, unsigned int options = ParseDefault, Mezzanine::XML::Encoding DocumentEncoding = EncodingAuto);
455 /// @endcode
456 /// These functions accept the file path as its first argument, and also two optional arguments, which specify parsing options (see Parsing options) and input data encoding ( see
457 /// @ref XMLLoadingEncodings ). The path has the target operating system format, so it can be a relative or absolute one, it should have the delimiters of the target system, it
458 /// should have the exact case if the target file system is case-sensitive, and is subject to any other restrictions of the underlying filesystem.
459 /// \n \n
460 /// File path is passed to the system file opening function as is in case of the first function (which accepts const char* path); the second function either uses a special file
461 /// opening function if it is provided by the runtime library or converts the path to UTF-8 and uses the system file opening function.
462 /// \n \n
463 /// Document::LoadFile destroys the existing document tree and then tries to load the new tree from the specified file. The result of the operation is returned in an
464 /// Mezzanine::XML::ParseResult object; this object contains the operation status and the related information (i.e. last successfully parsed position in the input file, if parsing
465 /// fails). See @ref XMLLoadingErrors for error handling details.
466 /// \n \n
467 /// This is an example of loading XML document from file:
468 /// @code
469 /// Mezzanine::XML::Document Doc;
470 /// Mezzanine::XML::ParseResult Result = Doc.LoadFile("tree.xml");
471 /// std::cout << "Load result: " << Result.Description() << std::endl;
472 /// @endcode
473 /// @subsection XMLLoadingFromMemory Loading document from memory
474 /// Sometimes XML data should be loaded from some other source than a file, i.e. HTTP URL; also you may want to load XML data from file using non-standard functions, i.e. to use
475 /// your virtual file system facilities or to load XML from gzip-compressed files. All these scenarios require loading document from memory. First you should prepare a contiguous
476 /// memory block with all XML data; then you have to invoke one of buffer loading functions. These functions will handle the necessary encoding conversions, if any, and then will
477 /// parse the data into the corresponding XML tree. There are several buffer loading functions, which differ in the behavior and thus in performance/memory usage:
478 /// @code
479 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::LoadBuffer (const void *contents, size_t size, unsigned int options=ParseDefault, Encoding DocumentEncoding=EncodingAuto);
480 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::LoadBufferInplace (void *contents, size_t size, unsigned int options=ParseDefault, Encoding DocumentEncoding=EncodingAuto);
481 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::LoadBufferInplaceOwn (void *contents, size_t size, unsigned int options=ParseDefault, Encoding DocumentEncoding=EncodingAuto)
482 /// @endcode
483 /// All functions accept the buffer which is represented by a pointer to XML data, contents, and data size in bytes. Also there are two optional arguments, which specify parsing
484 /// options ( see @ref XMLLoadingParsingOptions ) and input data encoding ( see @ref XMLLoadingEncodings ). The buffer does not have to be zero-terminated.
485 /// \n \n
486 /// Mezzanine::XML::Document::LoadBuffer function works with immutable buffer - it does not ever modify the buffer. Because of this restriction it has to create a private buffer and
487 /// copy XML data to it before parsing (applying encoding conversions if necessary). This copy operation carries a performance penalty, so inplace functions are provided -
488 /// Mezzanine::XML::Document::LoadBufferInplace and Mezzanine::XML::Document::LoadBufferInplaceOwn store the document data in the buffer, modifying it in the process. In order for the
489 /// document to stay valid, you have to make sure that the buffer's lifetime exceeds that of the tree if you're using inplace functions. In addition to that,
490 /// Mezzanine::XML::Document::LoadBufferInplace does not assume ownership of the buffer, so you'll have to destroy it yourself; Mezzanine::XML::Document::LoadBufferInplaceOwn assumes
491 /// ownership of the buffer and destroys it once it is not needed. This means that if you're using Mezzanine::XML::Document::LoadBufferInplaceOwn, you have to allocate memory with
492 /// Mezzanine::xml allocation function ( Not recomended, the Allocation API may be getting updates in the near future ).
493 /// \n \n
494 /// The best way from the performance/memory point of view is to load document using Mezzanine::XML::Document::LoadBufferInplaceOwn; this function has maximum control of the buffer
495 /// with XML data so it is able to avoid redundant copies and reduce peak memory usage while parsing. However, this is not recommendeded unless you have to load the document
496 /// from memory and performance is critical. Once the memory portion of the API has stabilized this will become the ideal
497 /// \n \n
498 /// There is also a simple helper function for cases when you want to load the XML document from null-terminated character string:
499 /// @code
500 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::Load(const char_t *contents, unsigned int options=ParseDefault);
501 /// @endcode
502 /// It is equivalent to calling Mezzanine::XML::Document::LoadBuffer with size being either strlen(contents) or wcslen(contents) * sizeof(wchar_t), depending on the character type.
503 /// This function assumes native encoding for input data, so it does not do any encoding conversion. In general, this function is fine for loading small documents from string
504 /// literals, but has more overhead and less functionality than the buffer loading functions.
505 /// \n \n
506 /// This is an example of loading XML document from memory using LoadBuffer:
507 /// @code
508 /// const char Source[] = "<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>";
509 /// size_t Size = sizeof(Source);
510 ///
511 /// // You can use LoadBuffer to load the document from an immutable memory block:
512 /// Mezzanine::XML::ParseResult Result = doc.LoadBuffer(Source, Size);
513 /// @endcode
514 /// This is an example of loading XML document from memory using LoadBufferInplace:
515 /// @code
516 /// const char Source[] = "<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>";
517 /// size_t Size = sizeof(Source);
518 ///
519 /// // You can use LoadBufferInplace to load document from mutable memory block
520 /// // the block's lifetime must exceed that of document
521 /// char* Buffer = new char[Size];
522 /// memcpy(Buffer, Source, Size);
523 ///
524 /// // The block can be allocated by any method; the block is modified during parsing
525 /// Mezzanine::XML::ParseResult Result = doc.LoadBufferInplace(Buffer, Size);
526 ///
527 /// // You have to destroy the block yourself after the document is no longer used
528 /// delete[] Buffer;
529 /// @endcode
530 /// This is an example of loading XML document from memory using Load and a string literal:
531 /// @code
532 /// // You can use Load to load document from null-terminated strings, for example literals:
533 /// Mezzanine::XML::ParseResult Result = doc.Load("<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>");
534 /// @endcode
535 /// @subsection XMLLoadingStreams Loading document from C++ IOstreams
536 /// To enhance interoperability, Mezzanine::xml provides functions for loading document from any object which implements C++ std::istream interface. This allows you to load documents
537 /// from any standard C++ stream (i.e. file stream) or any third-party compliant implementation (i.e. Boost Iostreams). There are two functions, one works with narrow character
538 /// streams, another handles wide character ones:
539 /// @code
540 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::Load (std::basic_istream< char, std::char_traits< char > > &stream, unsigned int options=ParseDefault, Encoding DocumentEncoding=EncodingAuto);
541 /// Mezzanine::XML::ParseResult Mezzanine::XML::Document::Load (std::basic_istream< wchar_t, std::char_traits< wchar_t > > &stream, unsigned int options=ParseDefault);
542 /// @endcode
543 /// Mezzanine::XML::Document::Load with std::istream argument loads the document from stream from the current read position to the end, treating the stream contents as a byte stream
544 /// of the specified encoding (with encoding autodetection as necessary). Thus calling Mezzanine::XML::Document::Load on an opened std::ifstream object is equivalent to calling
545 /// Mezzanine::XML::Document::LoadFile.
546 /// \n \n
547 /// Mezzanine::XML::Document::Load with std::wstream argument treats the stream contents as a wide character stream ( encoding is always @ref Mezzanine::XML::Encoding "Encoding::Encodingwchar_t" ).
548 /// Because of this, using Mezzanine::XML::Document::LoadFile with wide character streams requires careful (usually platform-specific) stream setup (i.e. using the imbue function).
549 /// Generally use of wide streams is discouraged, however it provides you the ability to load documents from non-Unicode encodings, i.e. you can load Shift-JIS encoded data if
550 /// you set the correct locale.
551 /// \n \n
552 /// This is a simple example of loading XML document from a file using streams read:
553 /// @code
554 /// std::ifstream Stream("weekly-utf-8.xml");
555 /// Mezzanine::XML::ParseResult Result = Doc.Load(Stream);
556 /// @endcode
557 /// Stream loading requires working seek/tell functions and therefore may fail when used with some stream implementations like gzstream.
558 /// \n \n
559 /// @subsection XMLLoadingErrors Handling Parsing Errors
560 /// All document loading functions return the parsing result via Mezzanine::XML::ParseResult object. It contains parsing status, the offset of last successfully parsed character from
561 /// the beginning of the source stream, and the encoding of the source stream.
562 /// \n \n
563 /// Parsing status is represented as the Mezzanine::XML::ParseStatus enumeration and can be one of the following:
564 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusOk" means that no error was encountered during parsing; the source stream represents the valid XML document which was
565 /// fully parsed and converted to a tree.
566 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusFileNotFound" is only returned by Document::LoadFile function and means that file could not be opened.
567 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusIOError" is returned by Document::LoadFile function and by load functions with std::istream/std::wstream arguments; it
568 /// means that some I/O error has occurred during reading the file/stream.
569 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusOutOfMemory" means that there was not enough memory during some allocation; any allocation failure during parsing results
570 /// in this error.
571 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusInternalError" means that something went horribly wrong; currently this error does not occur.
572 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusUnrecognizedTag" means that parsing stopped due to a tag with either an empty name or a name which starts with incorrect
573 /// character, such as #.
574 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusBadPi" means that parsing stopped due to incorrect document declaration/processing instruction.
575 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusBadComment, StatusBadCdata, StatusBadDocType and StatusBadPcdata" mean that parsing stopped due to the invalid construct
576 /// of the respective type
577 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusBadStartElement" means that parsing stopped because starting tag either had no closing > symbol or contained some incorrect
578 /// symbol
579 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusBadAttribute" means that parsing stopped because there was an incorrect attribute, such as an attribute without value or
580 /// with value that is not quoted (note that <node attr=1> is incorrect in XML)
581 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusBadEndElement" means that parsing stopped because ending tag had incorrect syntax (i.e. extra non-whitespace symbols between
582 /// tag name and >)
583 /// - @ref Mezzanine::XML::ParseStatus "ParseStatus::StatusEndElementMismatch" means that parsing stopped because the closing tag did not match the opening one (i.e. <node></nedo>)
584 /// or because some tag was not closed at all.
585 ///
586 /// Mezzanine::XML::ParseResult::Description member function can be used to convert parsing status to a string; the returned message is always in English, so you'll have to write your own
587 /// function if you need a localized string. However please note that the exact messages returned by the Description() function may change from version to version, so any complex
588 /// status handling should be based on the Status value.
589 /// \n \n
590 /// If parsing failed because the source data was not a valid XML, the resulting tree is not destroyed - despite the fact that load function returns error, you can use the part of the
591 /// tree that was successfully parsed. Obviously, the last element may have an unexpected name/value; for example, if the attribute value does not end with the necessary quotation
592 /// mark, like in <node attr="value>some data</node> example, the value of attribute attr will contain the string "value>some data</node>".
593 /// \n \n
594 /// In addition to the Status code, Mezzanine::XML::ParseResult has an Offset member, which contains the offset of last successfully parsed character if parsing failed because of an error
595 /// in source data; otherwise offset is 0. For parsing efficiency reasons, Mezzanine::xml does not track the current line during parsing; this offset is in units of Mezzanine::XML::char_t
596 /// (bytes for character mode, wide characters for wide character mode). Many text editors support 'Go To Position' feature - you can use it to locate the exact error position.
597 /// Alternatively, if you're loading the document from memory, you can display the error chunk along with the error description.
598 /// @warning Offset is calculated in the XML buffer in native encoding; if encoding conversion is performed during parsing, offset can not be used to reliably track the error position.
599 ///
600 /// Mezzanine::XML::ParseResult also has a DocumentEncoding member, which can be used to check that the source data encoding was correctly guessed. It is equal to the exact encoding used
601 /// during parsing (i.e. with the exact endianness); see @ref XMLLoadingEncodings for more information.
602 /// \n \n
603 /// A Mezzanine::XML::ParseResult object can be implicitly converted to bool; if you do not want to handle parsing errors thoroughly, you can just check the return value of load functions
604 /// as if it was a bool: if (doc.load_file("file.xml")) { //on Successful parse } else { //on failed parse }. A True is returned if parsing was successful.
605 /// \n \n
606 /// This is an example of handling loading errors:
607 /// @code
608 /// const char Source[] = "<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>";
609 /// Mezzanine::XML::Document Doc;
610 /// Mezzanine::XML::ParseResult Result = Doc.Load(Source);
611 ///
612 /// if (Result)
613 /// std::cout << "XML [" << Source << "] parsed without errors\n\n";
614 /// else
615 /// {
616 /// std::cout << "XML [" << Source << "] parsed with errors\n";
617 /// std::cout << "Error description: " << Result.Description() << "\n";
618 /// std::cout << "Error offset: " << Result.Offset << " (error at [..." << (Source + Result.Offset) << "]\n\n";
619 /// }
620 /// @endcode
621 /// @subsection XMLLoadingParsingOptions Parsing Options
622 /// All document loading functions accept the optional parameter options. This is a bitmask that customizes the parsing process: you can select the node types that are parsed and
623 /// various transformations that are performed with the XML text. Disabling certain transformations can improve parsing performance for some documents; however, the code for all
624 /// transformations is very well optimized, and thus the majority of documents won't get any performance benefit. As a general rule, only modify parsing flags if you want to get some
625 /// nodes in the document that are excluded by default (i.e. declaration or comment nodes).
626 /// @note You should use the usual bitwise arithmetic to manipulate the bitmask: to enable a flag, use mask | flag; to disable a flag, use mask & ~flag.
627 ///
628 /// These flags control the resulting tree contents:
629 /// - @ref Mezzanine::XML::ParseDeclaration determines if XML document declaration (node with type @ref Mezzanine::XML::NodeType "NodeDeclaration" ) is to be put in DOM tree. If this flag
630 /// is off, it is not put in the tree, but is still parsed and checked for correctness. This flag is off by default.
631 /// - @ref Mezzanine::XML::ParseDocType determines if XML document type declaration (node with type @ref Mezzanine::XML::NodeType "NodeDocType" ) is to be put in DOM tree. If this flag is
632 /// off, it is not put in the tree, but is still parsed and checked for correctness. This flag is off by default.
633 /// - @ref Mezzanine::XML::ParsePi determines if processing instructions (nodes with type @ref Mezzanine::XML::NodeType "NodePi" ) are to be put in DOM tree. If this flag is off, they are
634 /// not put in the tree, but are still parsed and checked for correctness. Note that "<?xml ...?>" (document declaration) is not considered to be a PI. This flag is off by default.
635 /// - @ref Mezzanine::XML::ParseComments determines if comments (nodes with type @ref Mezzanine::XML::NodeType "NodeComment" ) are to be put in DOM tree. If this flag is off, they are not
636 /// put in the tree, but are still parsed and checked for correctness. This flag is off by default.
637 /// - @ref Mezzanine::XML::ParseCdata determines if CDATA sections (nodes with type @ref Mezzanine::XML::NodeType "NodeCdata" ) are to be put in DOM tree. If this flag is off, they are not
638 /// put in the tree, but are still parsed and checked for correctness. This flag is on by default.
639 /// - @ref Mezzanine::XML::ParseWsPcdata determines if PCDATA nodes (nodes with type @ref Mezzanine::XML::NodeType "NodePcdata" ) that consist only of whitespace characters are to be put
640 /// in DOM tree. Often whitespace-only data is not significant for the application, and the cost of allocating and storing such nodes (both memory and speed-wise) can be
641 /// significant. For example, after parsing XML string "<node> <a/> </node>, <node>" element will have three children when Mezzanine::XML::ParseWsPcdata is set (child with type
642 /// @ref Mezzanine::XML::NodeType "NodePcdata" and value " ", child with type @ref Mezzanine::XML::NodeType "NodeElement" and name "a", and another child with type
643 /// @ref Mezzanine::XML::NodeType "NodePcdata" and value " "), and only one child when Mezzanine::XML::ParseWsPcdata is not set. This flag is off by default.
644 ///
645 /// These flags control the transformation of tree element contents:
646 /// - @ref Mezzanine::XML::ParseEscapes determines if character and entity references are to be expanded during the parsing process. Character references have the form \&#...; or
647 /// \&#x...; (... is Unicode numeric representation of character in either decimal ( \&#...; ) or hexadecimal ( \&#x...; ) form), entity references are \&lt;, \&gt;, \&amp;,
648 /// \&apos; and \&quot; (note that as Mezzanine::xml does not handle DTD, the only allowed entities are predefined ones). If character/entity reference can not be expanded, it is
649 /// left as is, so you can do additional processing later. Reference expansion is performed on attribute values and PCDATA content. This flag is on by default.
650 /// - @ref Mezzanine::XML::ParseEol determines if EOL handling (that is, replacing sequences 0x0d 0x0a by a single 0x0a character, and replacing all standalone 0x0d characters by
651 /// 0x0a) is to be performed on input data (that is, comments contents, PCDATA/CDATA contents and attribute values). If this is set all \\r \\n will replaced with \\n.
652 /// This flag is on by default.
653 /// - @ref Mezzanine::XML::ParseWconvAttribute determines if attribute value normalization should be performed for all attributes. This means, that whitespace characters (new line,
654 /// tab and space) are replaced with space (' '). New line characters are always treated as if Mezzanine::XML::ParseEol is set, i.e. \\r \\n is converted to a single space. This
655 /// flag is on by default.
656 /// - @ref Mezzanine::XML::ParseWnormAttribute determines if extended attribute value normalization should be performed for all attributes. This means, that after attribute values
657 /// are normalized as if Mezzanine::XML::ParseWconvAttribute was set, leading and trailing space characters are removed, and all sequences of space characters are replaced by a
658 /// single space character. The value of Mezzanine::XML::ParseWconvAttribute was set has no effect if this flag is on. This flag is off by default.
659 ///
660 /// @note Mezzanine::XML::ParseWconvAttribute option performs transformations that are required by W3C specification for attributes that are declared as CDATA; ParseWnormAttribute performs
661 /// transformations required for NMTOKENS attributes. In the absence of document type declaration all attributes should behave as if they are declared as CDATA, thus
662 /// Mezzanine::XML::ParseWconvAttribute is the default option.
663 ///
664 /// Additionally there are three predefined option masks:
665 /// - Mezzanine::XML::ParseMinimal has all options turned off. This option mask means that Mezzanine::xml does not add declaration nodes, document type declaration nodes, PI nodes,
666 /// CDATA sections and comments to the resulting tree and does not perform any conversion for input data, so theoretically it is the fastest mode. However, as mentioned above,
667 /// in practice Mezzanine::XML::ParseDefault is usually equally fast.
668 /// - Mezzanine::XML::ParseDefault is the default set of flags, i.e. it has all options set to their default values. It includes parsing CDATA sections (comments/PIs are not parsed),
669 /// performing character and entity reference expansion, replacing whitespace characters with spaces in attribute values and performing EOL handling. Note, that PCDATA sections
670 /// consisting only of whitespace characters are not parsed (by default) for performance reasons.
671 /// - Mezzanine::XML::ParseFull is the set of flags which adds nodes of all types to the resulting tree and performs default conversions for input data. It includes parsing CDATA
672 /// sections, comments, PI nodes, document declaration node and document type declaration node, performing character and entity reference expansion, replacing whitespace
673 /// characters with spaces in attribute values and performing EOL handling. Note, that PCDATA sections consisting only of whitespace characters are not parsed in this mode.
674 ///
675 /// This is an example of using different parsing options:
676 /// @code
677 /// const char* Source = "<!--comment--><node>&lt;</node>";
678 ///
679 /// // Parsing with default options; note that comment node is not added to the tree, and entity reference &lt; is expanded
680 /// Doc.Load(Source);
681 /// std::cout << "First node value: [" << Doc.GetFirstChild().Value() << "], node child value: [" << Doc.ChildValue("node") << "]\n";
682 ///
683 /// // Parsing with additional value option; comment node is now added to the tree
684 /// Doc.Load(Source, Mezzanine::XML::ParseDefault | Mezzanine::XML::ParseComments);
685 /// std::cout << "First node value: [" << Doc.GetFirstChild().Value() << "], node child value: [" << Doc.ChildValue("node") << "]\n";
686 ///
687 /// // Parsing with additional value option and without the (default) parse_escapes option; &lt; is not expanded
688 /// Doc.Load(Source, (Mezzanine::XML::ParseDefault | Mezzanine::XML::ParseComments) & ~Mezzanine::XML::ParseEscapes);
689 /// std::cout << "First node value: [" << Doc.GetFirstChild().Value() << "], node child value: [" << Doc.ChildValue("node") << "]\n";
690 ///
691 /// // Parsing with minimal option mask; comment node is not added to the tree, and &lt; is not expanded
692 /// Doc.Load(Source, Mezzanine::XML::ParseMinimal);
693 /// std::cout << "First node value: [" << Doc.GetFirstChild().Value() << "], node child value: [" << Doc.ChildValue("node") << "]\n";
694 /// @endcode
695 /// @subsection XMLLoadingEncodings Encodings
696 /// Mezzanine::xml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little endian), UTF-32 (big and little endian); UCS-2 is naturally supported since it's a strict subset
697 /// of UTF-16) and handles all encoding conversions. Most loading functions accept the optional parameter encoding. This is a value of enumeration type Mezzanine::XML::Encoding, that
698 /// can have the following values:
699 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingAuto" means that pugixml will try to guess the encoding based on source XML data. The algorithm is a modified version of the
700 /// one presented in Appendix F.1 of XML recommendation; it tries to match the first few bytes of input data with the following patterns in strict order:
701 /// - If first four bytes match UTF-32 BOM (Byte Order Mark), encoding is assumed to be UTF-32 with the endianness equal to that of BOM;
702 /// - If first two bytes match UTF-16 BOM, encoding is assumed to be UTF-16 with the endianness equal to that of BOM;
703 /// - If first three bytes match UTF-8 BOM, encoding is assumed to be UTF-8;
704 /// - If first four bytes match UTF-32 representation of <, encoding is assumed to be UTF-32 with the corresponding endianness;
705 /// - If first four bytes match UTF-16 representation of <?, encoding is assumed to be UTF-16 with the corresponding endianness;
706 /// - If first two bytes match UTF-16 representation of <, encoding is assumed to be UTF-16 with the corresponding endianness (this guess may yield incorrect result,
707 /// but it's better than UTF-8);
708 /// - Otherwise encoding is assumed to be UTF-8.
709 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingUTF8" corresponds to UTF-8 encoding as defined in the Unicode standard; UTF-8 sequences with length equal to 5 or 6 are not
710 /// standard and are rejected.
711 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingUTF16LE" corresponds to little-endian UTF-16 encoding as defined in the Unicode standard; surrogate pairs are supported.
712 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingUTF16BE" corresponds to big-endian UTF-16 encoding as defined in the Unicode standard; surrogate pairs are supported.
713 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingUTF16" corresponds to UTF-16 encoding as defined in the Unicode standard; the endianness is assumed to be that of the target
714 /// platform.
715 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingUTF32LE" corresponds to little-endian UTF-32 encoding as defined in the Unicode standard.
716 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingUTF32BE" corresponds to big-endian UTF-32 encoding as defined in the Unicode standard.
717 /// - @ref Mezzanine::XML::Encoding "Encoding::EncodingUTF32" corresponds to UTF-32 encoding as defined in the Unicode standard; the endianness is assumed to be that of the target
718 /// platform.
719 /// - @ref Mezzanine::XML::Encoding "Encoding::Encodingwchar_t " corresponds to the encoding of Mezzanine::XML::wchar_t type; it has the same meaning as either
720 /// @ref Mezzanine::XML::Encoding "EncodingUTF16" or @ref Mezzanine::XML::Encoding "EncodingUTF32", depending on Mezzanine::XML::wchar_t size.
721 ///
722 /// The algorithm used for @ref Mezzanine::XML::Encoding "EncodingAuto" correctly detects any supported Unicode encoding for all well-formed XML documents (since they start with document
723 /// declaration) and for all other XML documents that start with <; if your XML document does not start with < and has encoding that is different from UTF-8, use the specific encoding.
724 /// @note The current behavior for Unicode conversion is to skip all invalid UTF sequences during conversion. This behavior should not be relied upon; moreover, in case no encoding
725 /// conversion is performed, the invalid sequences are not removed, so you'll get them as is in node/attribute contents.
726 ///
727 /// @subsection XMLLoadingStandards Conformance to W3C Specification
728 /// Mezzanine::xml is not fully W3C conformant - it can load any valid XML document, but does not perform some well-formedness checks. While considerable effort is made to reject invalid
729 /// XML documents, some validation is not performed because of performance reasons.
730 /// \n \n There is only one non-conformant behavior when dealing with valid XML documents, Mezzanine::xml does not use information supplied in document type declaration for parsing. This
731 /// means that entities declared in DOCTYPE are not expanded, and all attribute/PCDATA values are always processed in a uniform way that depends only on parsing options.
732 /// \n \n
733 /// As for rejecting invalid XML documents, there are a number of incompatibilities with W3C specification, including:
734 /// - Multiple attributes of the same node can have equal names.
735 /// - All non-ASCII characters are treated in the same way as symbols of English alphabet, so some invalid tag names are not rejected.
736 /// - Attribute values which contain < are not rejected.
737 /// - Invalid entity/character references are not rejected and are instead left as is.
738 /// - Comment values can contain --.
739 /// - XML data is not required to begin with document declaration; additionally, document declaration can appear after comments and other nodes.
740 /// - Invalid document type declarations are silently ignored in some cases.
741 ///
742 /// @section XMLAccessing Accessing Document Data
743 /// - @ref XMLAccessingBasics
744 /// - @ref XMLAccessingNodeData
745 /// - @ref XMLAccessingAttributeData
746 /// - @ref XMLAccessingContentBased
747 /// - @ref XMLAccessingIterators
748 /// - @ref XMLAccessingWalker
749 /// - @ref XMLAccessingPredicates
750 /// - @ref XMLAccessingMisc
751 ///
752 /// Mezzanine::xml features an extensive interface for getting various types of data from the document and for traversing the document. This section provides documentation for all such
753 /// functions that do not modify the tree except for XPath-related functions; see @ref XMLXPath for XPath reference. As discussed in @ref XMLInterface, there are two types of handles
754 /// to tree data - Mezzanine::XML::Node and Mezzanine::XML::Attribute. The handles have special null (empty) values which propagate through various functions and thus are useful for writing
755 /// more concise code; see @ref XMLInterface for details. The documentation in this section will explicitly state the results of all function in case of null inputs.
756 /// @subsection XMLAccessingBasics Basic traversal functions
757 /// The internal representation of the document is a tree, where each node has a list of child nodes (the order of children corresponds to their order in the XML representation),
758 /// additionally element nodes have a list of attributes, which is also ordered. Several functions are provided in order to let you get from one node in the tree to the other. These
759 /// functions roughly correspond to the internal representation, and thus are usually building blocks for other methods of traversing (i.e. XPath traversals are based on these
760 /// functions).
761 /// @code
762 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetParent() const;
763 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetFirstChild() const;
764 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetLastChild() const;
765 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetNextSibling() const;
766 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetPreviousSibling() const;
767 ///
768 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::GetFirstAttribute() const;
769 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::GetLastAttribute() const;
770 /// Mezzanine::XML::Attribute Mezzanine::XML::Attribute::GetNextAttribute() const;
771 /// Mezzanine::XML::Attribute Mezzanine::XML::Attribute::GetPreviousAttribute() const;
772 /// @endcode
773 /// The GetParent function returns the node's parent; all non-null nodes except the document have non-null parent. GetFirstChild and GetLastChild return the first and last child of the
774 /// node, respectively; note that only document nodes and element nodes can have non-empty child node list. If node has no children, both functions return null nodes. GetNextSibling
775 /// and GetPreviousSibling return the node that's immediately to the right/left of this node in the children list, respectively - for example, in <a/> <b/> <c/>, calling GetNextSibling
776 /// for a handle that points to <b/> results in a handle pointing to <c/>, and calling GetPreviousSibling results in handle pointing to <a/>. If node does not have next/previous sibling
777 /// (this happens if it is the last/first node in the list, respectively), the functions return null nodes. GetFirstAttribute, GetLastAttribute, GetNextAttribute and GetPreviousAttribute
778 /// functions behave similarly to the corresponding child node functions and allow to iterate through attribute list in the same way.
779 /// @note Because of memory consumption reasons, attributes do not have a link to their parent nodes. Thus there is no Mezzanine::XML::attribute::parent() function.
780 ///
781 /// Calling any of the functions above on the null handle results in a null handle - i.e. node.GetFirstChild().GetNextSibling() returns the second child of node, and null handle if node
782 /// is null, has no children at all or if it has only one child node.
783 /// \n \n
784 /// With these functions, you can iterate through all child nodes and display all attributes like this:
785 /// @code
786 /// for (Mezzanine::XML::Node tool = tools.GetFirstChild(); tool; tool = tool.GetNextSibling())
787 /// {
788 /// std::cout << "Tool:";
789 ///
790 /// for (Mezzanine::XML::Attribute attr = tool.GetFirstAttribute(); attr; attr = attr.GetNextAttribute())
791 /// {
792 /// std::cout << " " << attr.Name() << "=" << attr.Value();
793 /// }
794 ///
795 /// std::cout << std::endl;
796 /// }
797 /// @endcode
798 /// @subsection XMLAccessingNodeData Getting Node Data
799 /// Apart from structural information (parent, child nodes, attributes), nodes can have name and value, both of which are strings. Depending on node type, name or value may be absent.
800 /// @ref Mezzanine::XML::NodeType "NodeDocument" nodes do not have a name or value, @ref Mezzanine::XML::NodeType "NodeElement" and @ref Mezzanine::XML::NodeType "NodeType::NodeDeclaration" nodes
801 /// always have a name but never have a value, @ref Mezzanine::XML::NodeType "NodeType::NodePcdata", @ref Mezzanine::XML::NodeType "NodeType::NodeCdata",
802 /// @ref Mezzanine::XML::NodeType "NodeType::NodeComment" and @ref Mezzanine::XML::NodeType "NodeType::NodeDocType" nodes never have a name but always have a value (it may be empty though),
803 /// @ref Mezzanine::XML::NodeType "NodeType::NodePi" nodes always have a name and a value (again, value may be empty). In order to get node's name or value, you can use the following
804 /// functions:
805 /// @code
806 /// const char_t* Mezzanine::XML::Node::Name() const;
807 /// const char_t* Mezzanine::XML::Node::Value() const;
808 /// @endcode
809 /// In case node does not have a name or value or if the node handle is null, both functions return empty strings - they never return null pointers.
810 /// \n \n
811 /// It is common to store data as text contents of some node - i.e. <node> <description> This is a node </description> </node>. In this case, <description> node does not have
812 /// a value, but instead has a child of type @ref Mezzanine::XML::NodeType "NodeType::NodePcdata" with value "This is a node". Mezzanine::xml provides two helper functions to parse such data:
813 /// @code
814 /// const char_t* Mezzanine::XML::Node::ChildValue() const;
815 /// const char_t* Mezzanine::XML::Node::ChildValue(const char_t* name) const;
816 /// @endcode
817 /// ChildValue() returns the value of the first child with type @ref Mezzanine::XML::NodeType "NodeType::NodePcdata" or @ref Mezzanine::XML::NodeType "NodeType::NodeCdata";
818 /// ChildValue(Name) is a simple wrapper for Child(Name).ChildValue(). For the above example, calling node.ChildValue("description") and description.ChildValue() will both produce
819 /// string "This is a node". If there is no child with relevant type, or if the handle is null, ChildValue functions return empty string.
820 /// \n \n
821 /// There is an example of using some of these functions @ref XMLAccessingAttributeData "at the end of the next section".
822 /// @subsection XMLAccessingAttributeData Getting attribute data
823 /// All attributes have name and value, both of which are strings (value may be empty). There are two corresponding accessors:
824 /// @code
825 /// const char_t* Mezzanine::XML::Attribute::Name() const;
826 /// const char_t* Mezzanine::XML::Attribute::Value() const;
827 /// @endcode
828 /// In case the attribute handle is null, both functions return empty strings - they never return null pointers.
829 /// \n \n
830 /// In many cases attribute values have types that are not strings - i.e. an attribute may always contain values that should be treated as integers, despite the fact that they are
831 /// represented as strings in XML. Mezzanine::xml provides several accessors that convert attribute value to some other type:
832 /// @code
833 /// // Native C++ types
834 /// bool Mezzanine::XML::Attribute::AsBool() const;
835 /// double Mezzanine::XML::Attribute::AsDouble() const;
836 /// float Mezzanine::XML::Attribute::AsFloat() const;
837 /// int Mezzanine::XML::Attribute::AsInt() const;
838 /// unsigned int Mezzanine::XML::Attribute::AsUint() const;
839 ///
840 /// //Mezzanine abstracted types
841 /// Real Mezzanine::XML::Attribute::AsReal() const;
842 /// String Mezzanine::XML::Attribute::AsString() const;
843 /// Whole Mezzanine::XML::Attribute::AsWhole() const;
844 /// @endcode
845 /// AsDouble, AsFloat, AsInt, AsUint, AsReal and AsWhole convert attribute values to numbers. If attribute handle is null or attribute value is empty, 0 is returned. Otherwise, all
846 /// leading whitespace characters are truncated, and the remaining string is parsed as a decimal number (AsInt, AsUint or AsWhole) or as a floating point number in either decimal
847 /// or scientific form (AsDouble, AsFloat or AsReal). Any extra characters are silently discarded, i.e. AsInt will return 1 for string "1abc".
848 /// \n \n
849 /// In case the input string contains a number that is out of the target numeric range, the result is undefined.
850 /// @warning Some number conversion functions depend on current C locale as set with setlocale, so may return unexpected results if the locale is different from "C".
851 ///
852 /// AsBool converts attribute value to boolean as follows: if attribute handle is null or attribute value is empty, false is returned. Otherwise, true is returned if the first
853 /// character is one of '1', 't', 'T', 'y', 'Y'. This means that strings like "true" and "yes" are recognized as true, while strings like "false" and "no" are recognized as false.
854 /// For more complex matching you'll have to write your own function.
855 /// @note There are no portable 64-bit types in C++, so there is no corresponding conversion function. If your platform has a 64-bit integer, you can easily write a conversion
856 /// function yourself. We are planning on addressing this with a new Mezzanine abstracted type, but we have not done so yet.
857 ///
858 /// This is an example of using these functions, along with node data retrieval ones:
859 /// @code
860 /// for (Mezzanine::XML::Node tool = tools.GetChild("Tool"); tool; tool = tool.GetNextSibling("Tool"))
861 /// {
862 /// std::cout << "Tool " << tool.GetAttribute("Filename").Value();
863 /// std::cout << ": AllowRemote " << tool.GetAttribute("AllowRemote").AsBool();
864 /// std::cout << ", Timeout " << tool.GetAttribute("Timeout").AsInt();
865 /// std::cout << ", Description '" << tool.ChildValue("Description") << "'\n";
866 /// }
867 /// @endcode
868 /// @subsection XMLAccessingContentBased Content Based Traversal Functions
869 /// Since a lot of document traversal consists of finding the node/attribute with the correct name, there are special functions for that purpose:
870 /// @code
871 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetChild(const char_t* name) const;
872 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::GetAttribute(const char_t* name) const;
873 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetNextSibling(const char_t* name) const;
874 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetPreviousSibling(const char_t* name) const;
875 /// @endcode
876 /// GetChild and GetAttribute return the first child/attribute with the specified name; GetNextSibling and GetPreviousSibling return the first sibling in the corresponding direction
877 /// with the specified name. All string comparisons are case-sensitive. In case the node handle is null or there is no node/attribute with the specified name, null handle is returned.
878 /// \n \n
879 /// GetChild and GetNextSibling functions can be used together to loop through all child nodes with the desired name like this:
880 /// @code
881 /// for (Mezzanine::XML::Node tool = tools.GetChild("Tool"); tool; tool = tool.GetNextSibling("Tool"))
882 /// {}
883 /// @endcode
884 /// Occasionally the needed node is specified not by the unique name but instead by the value of some attribute; for example, it is common to have node collections with each node
885 /// having a unique id: <group> <item id="1"/> <item id="2"/> </group>. There are two functions for finding child nodes based on the attribute values:
886 /// @code
887 /// Mezzanine::XML::Node Mezzanine::XML::Node::FindChildbyAttribute(const char_t* name, const char_t* attr_name, const char_t* attr_value) const;
888 /// Mezzanine::XML::Node Mezzanine::XML::Node::FindChildbyAttribute(const char_t* attr_name, const char_t* attr_value) const;
889 /// @endcode
890 /// The three-argument function returns the first child node with the specified name which has an attribute with the specified name/value; the two-argument function skips the name
891 /// test for the node, which can be useful for searching in heterogeneous collections. If the node handle is null or if no node is found, null handle is returned. All string
892 /// comparisons are case-sensitive.
893 /// \n \n
894 /// In all of the above functions, all arguments have to be valid strings; passing null pointers results in undefined behavior.
895 ///
896 /// This is an example of using these functions:
897 /// @code
898 /// std::cout << "Tool for *.dae generation: " << tools.FindChildbyAttribute("Tool", "OutputFileMasks", "*.dae").GetAttribute("Filename").Value() << "\n";
899 ///
900 /// for (Mezzanine::XML::Node tool = tools.GetChild("Tool"); tool; tool = tool.GetNextSibling("Tool"))
901 /// {
902 /// std::cout << "Tool " << tool.GetAttribute("Filename").Value() << "\n";
903 /// }
904 /// @endcode
905 /// @subsection XMLAccessingIterators Traversing Node/Attribute Lists via Iterators
906 /// Child node lists and attribute lists are simply double-linked lists; while you can use GetPreviousSibling/GetNextSibling and other such functions for iteration, Mezzanine::xml
907 /// additionally provides node and attribute iterators, so that you can treat nodes as containers of other nodes or attributes:
908 /// @code
909 /// class Mezzanine::XML::NodeIterator;
910 /// class Mezzanine::XML::AttributeIterator;
911 ///
912 /// typedef Mezzanine::XML::NodeIterator Mezzanine::XML::Node::iterator;
913 /// iterator Mezzanine::XML::Node::begin() const;
914 /// iterator Mezzanine::XML::Node::end() const;
915 ///
916 /// typedef Mezzanine::XML::AttributeIterator Mezzanine::XML::Node::attribute_iterator;
917 /// attribute_iterator Mezzanine::XML::Node::attributes_begin() const;
918 /// attribute_iterator Mezzanine::XML::Node::attributes_end() const;
919 /// @endcode
920 /// begin and attributes_begin return iterators that point to the first node/attribute, respectively; end and attributes_end return past-the-end iterator for node/attribute list,
921 /// respectively - this iterator can't be dereferenced, but decrementing it results in an iterator pointing to the last element in the list (except for empty lists, where decrementing
922 /// past-the-end iterator results in undefined behavior). Past-the-end iterator is commonly used as a termination value for iteration loops (see sample below). If you want to get an
923 /// iterator that points to an existing handle, you can construct the iterator with the handle as a single constructor argument, like so: Mezzanine::XML::NodeIterator(node). For
924 /// Mezzanine::XML::AttributeIterator, you'll have to provide both an attribute and its parent node.
925 /// \n \n
926 /// begin and end return equal iterators if called on null node; such iterators can't be dereferenced. attributes_begin and attributes_end behave the same way. For correct iterator
927 /// usage this means that child node/attribute collections of null nodes appear to be empty.
928 /// @note The names begin, end, attribute_begin and attribute_end were chosen for maximum compatibility. Some template functions that act on containers rely on the name begin and end.
929 /// We may develop a naming scheme that fits better into the existing API in the future.
930 ///
931 /// Both types of iterators have bidirectional iterator semantics (i.e. they can be incremented and decremented, but efficient random access is not supported) and support all usual
932 /// iterator operations - comparison, dereference, etc. The iterators are invalidated if the node/attribute objects they're pointing to are removed from the tree; adding
933 /// nodes/attributes does not invalidate any iterators.
934 /// \n \n
935 /// Here is an example of using iterators for document traversal:
936 /// @code
937 /// for (Mezzanine::XML::NodeIterator it = tools.begin(); it != tools.end(); ++it)
938 /// {
939 /// std::cout << "Tool:";
940 ///
941 /// for (Mezzanine::XML::AttributeIterator ait = it->attributes_begin(); ait != it->attributes_end(); ++ait)
942 /// {
943 /// std::cout << " " << ait->Name() << "=" << ait->Value();
944 /// }
945 ///
946 /// std::cout << std::endl;
947 /// }
948 /// @endcode
949 /// @warning Node and attribute iterators are somewhere in the middle between const and non-const iterators. While dereference operation yields a non-constant reference to the object,
950 /// so that you can use it for tree modification operations, modifying this reference by assignment - i.e. passing iterators to a function like std::sort - will not give expected results,
951 /// as assignment modifies local handle that's stored in the iterator.
952 ///
953 /// @subsection XMLAccessingWalker Recursive traversal with Mezzanine::XML::TreeWalker
954 /// The methods described above allow traversal of immediate children of some node; if you want to do a deep tree traversal, you'll have to do it via a recursive function or some
955 /// equivalent method. However, pugixml provides a helper for depth-first traversal of a subtree. In order to use it, you have to implement the Mezzanine::XML::TreeWalker interface and to
956 /// call the Mezzanine::XML::Node::Traverse function.
957 /// @code
958 /// bool Mezzanine::XML::Node::Traverse(Mezzanine::XML::TreeWalker& walker);
959 /// @endcode
960 /// The traversal is launched by calling traverse function on traversal root and proceeds as follows:
961 /// - First, TreeWalker::begin function is called with traversal root as its argument.
962 /// - Then, TreeWalker::for_each function is called for all nodes in the traversal subtree in depth first order, excluding the traversal root. Node is passed as an argument.
963 /// - Finally, TreeWalker::end function is called with traversal root as its argument.
964 ///
965 /// @warning The Names of the Treewalker could change without notice prior to the initial of the engine.
966 ///
967 /// If begin, end or any of the for_each calls return false, the traversal is terminated and false is returned as the traversal result; otherwise, the traversal results in true.
968 /// Note that you don't have to override begin or end functions; their default implementations return true.
969 /// \n \n
970 /// You can get the node's depth relative to the traversal root at any point by calling TreeWalker::Depth function. It returns -1 if called from begin/end, and returns 0-based depth if
971 /// called from TreeWalker::for_each - depth is 0 for all children of the traversal root, 1 for all grandchildren and so on.
972 /// \n \n
973 /// This is an example of traversing tree hierarchy with Mezzanine::XML::TreeWalker:
974 /// @code
975 /// struct SimpleWalker: Mezzanine::XML::TreeWalker
976 /// {
977 /// virtual bool for_each(Mezzanine::XML::Node& node)
978 /// {
979 /// for (int i = 0; i < Depth(); ++i) std::cout << " "; // indentation
980 ///
981 /// std::cout << ": Name='" << node.Name() << "', Value='" << node.Value() << "'\n";
982 ///
983 /// return true; // continue traversal
984 /// }
985 /// };
986 /// @endcode
987 /// @code
988 /// SimpleWalker walker;
989 /// Doc.Traverse(walker);
990 /// @endcode
991 /// @subsection XMLAccessingPredicates Searching for Nodes/Attributes with Predicates
992 /// While there are existing functions for getting a node/attribute with known contents, they are often not sufficient for simple queries. As an alternative for manual iteration
993 /// through nodes/attributes until the needed one is found, you can make a predicate and call one of Find functions:
994 /// @code
995 /// template <typename Predicate> Mezzanine::XML::Attribute Mezzanine::XML::Node::FindAttribute(Predicate pred) const;
996 /// template <typename Predicate> Mezzanine::XML::Node Mezzanine::XML::Node::FindChild(Predicate pred) const;
997 /// template <typename Predicate> Mezzanine::XML::Node Mezzanine::XML::Node::FindNode(Predicate pred) const;
998 /// @endcode
999 /// The predicate should be either a plain function or a function object which accepts one argument of type Mezzanine::XML::Attribute (for FindAttribute) or Mezzanine::XML::Node (for FindChild
1000 /// and FindNode), and returns bool. The predicate is never called with null handle as an argument.
1001 /// \n \n
1002 /// Mezzanine::XML::Node::FindAttribute function iterates through all attributes of the specified node, and returns the first attribute for which the predicate returned true. If the
1003 /// predicate returned false for all attributes or if there were no attributes (including the case where the node is null), null attribute is returned.
1004 /// \n \n
1005 /// Mezzanine::XML::Node::FindChild function iterates through all child nodes of the specified node, and returns the first node for which the predicate returned true. If the predicate
1006 /// returned false for all nodes or if there were no child nodes (including the case where the node is null), null node is returned.
1007 /// \n \n
1008 /// Mezzanine::XML::Node::FindNode function performs a depth-first traversal through the subtree of the specified node (excluding the node itself), and returns the first node for which
1009 /// the predicate returned true. If the predicate returned false for all nodes or if subtree was empty, null node is returned.
1010 /// \n \n
1011 /// Here are some sample predicates:
1012 /// @code
1013 /// bool SmallTimeout(Mezzanine::XML::Node node)
1014 /// {
1015 /// return node.GetAttribute("Timeout").AsInt() < 20;
1016 /// }
1017 ///
1018 /// struct AllowRemotePredicate
1019 /// {
1020 /// bool operator()(Mezzanine::XML::Attribute attr) const
1021 /// {
1022 /// return strcmp(attr.Name(), "AllowRemote") == 0;
1023 /// }
1024 ///
1025 /// bool operator()(Mezzanine::XML::Node node) const
1026 /// {
1027 /// return node.GetAttribute("AllowRemote").AsBool();
1028 /// }
1029 /// };
1030 /// @endcode
1031 /// This is an example of using predicate-based functions:
1032 /// @code
1033 /// // Find child via predicate (looks for direct children only)
1034 /// std::cout << tools.FindChild(AllowRemotePredicate()).GetAttribute("Filename").Value() << std::endl;
1035 ///
1036 /// // Find node via predicate (looks for all descendants in depth-first order)
1037 /// std::cout << doc.FindNode(AllowRemotePredicate()).GetAttribute("Filename").Value() << std::endl;
1038 ///
1039 /// // Find attribute via predicate
1040 /// std::cout << tools.LastChild().FindAttribute(AllowRemotePredicate()).Value() << std::endl;
1041 ///
1042 /// // We can use simple functions instead of function objects
1043 /// std::cout << tools.FindChild(SmallTimeout).GetAttribute("Filename").Value() << std::endl;
1044 /// @endcode
1045 /// @subsection XMLAccessingMisc Miscellaneous functions
1046 /// If you need to get the document root of some node, you can use the following function:
1047 /// @code
1048 /// Mezzanine::XML::Node Mezzanine::XML::Node::GetRoot() const;
1049 /// @endcode
1050 /// This function returns the node with type @ref Mezzanine::XML::NodeType "NodeDocument", which is the root node of the document the node belongs to (unless the node is null, in which
1051 /// case null node is returned).
1052 /// \n \n
1053 /// While Mezzanine::xml supports complex XPath expressions, sometimes a simple path handling facility is needed. There are two functions, for getting node path and for converting path
1054 /// to a node:
1055 /// @code
1056 /// Mezzanine::String Mezzanine::XML::Node::Path(char_t delimiter = '/') const;
1057 /// Mezzanine::XML::Node Mezzanine::XML::Node::FirstElementByPath(const char_t* Path, char_t delimiter = '/') const;
1058 /// @endcode
1059 /// Node paths consist of node names, separated with a delimiter (which is / by default); also paths can contain self (.) and parent (..) pseudo-names, so that this is a valid path:
1060 /// "../../foo/./bar". path returns the path to the node from the document root, FirstElementByPath looks for a node represented by a given path; a path can be an absolute one
1061 /// (absolute paths start with the delimiter), in which case the rest of the path is treated as document root relative, and relative to the given node. For example, in the following
1062 /// document: <a> <b> <c/> </b> </a>, node <c/> has path "a/b/c"; calling FirstElementByPath for document with path "a/b" results in node <b/>; calling FirstElementByPath for
1063 /// node <a/> with path "../a/./b/../." results in node <a/>; calling FirstElementByPath with path "/a" results in node <a/> for any node.
1064 /// \n \n
1065 /// In case path component is ambiguous (if there are two nodes with given name), the first one is selected; paths are not guaranteed to uniquely identify nodes in a document. If any
1066 /// component of a path is not found, the result of FirstElementByPath is null node; also FirstElementByPath returns null node for null nodes, in which case the path does not matter.
1067 /// path returns an empty string for null nodes.
1068 ///
1069 /// Mezzanine::xml does not record row/column information for nodes upon parsing for efficiency reasons. However, if the node has not changed in a significant way since parsing (the
1070 /// name/value are not changed, and the node itself is the original one, i.e. it was not deleted from the tree and re-added later), it is possible to get the offset from the
1071 /// beginning of XML buffer:
1072 /// @code
1073 /// ptrdiff_t Mezzanine::XML::node::OffSetDebug() const;
1074 /// @endcode
1075 /// If the offset is not available (this happens if the node is null, was not originally parsed from a stream, or has changed in a significant way), the function returns -1. Otherwise
1076 /// it returns the offset to node's data from the beginning of XML buffer in Mezzanine::XML::char_t units. For more information on parsing offsets, see parsing error handling documentation.
1077 /// \n \n
1078 /// @section XMLModifying Modifiying Documents
1079 /// - @ref XMLModifyingNodeData
1080 /// - @ref XMLModifyingAttributeData
1081 /// - @ref XMLModifyingAdding
1082 /// - @ref XMLModifyingRemoving
1083 /// - @ref XMLModifyingCloning
1084 ///
1085 /// The document in Mezzanine::xml is fully mutable: you can completely change the document structure and modify the data of nodes/attributes. This section provides documentation for the
1086 /// relevant functions. All functions take care of memory management and structural integrity themselves, so they always result in structurally valid tree - however, it is possible to
1087 /// create an invalid XML tree (for example, by adding two attributes with the same name or by setting attribute/node name to empty/invalid string). Tree modification is optimized for
1088 /// performance and for memory consumption, so if you have enough memory you can create documents from scratch with Mezzanine::xml and later save them to file/stream instead of relying on
1089 /// error-prone manual text writing and without too much overhead.
1090 /// \n \n
1091 /// All member functions that change node/attribute data or structure are non-constant and thus can not be called on constant handles. However, you can easily convert constant handle
1092 /// to non-constant one by simple assignment: void foo(const Mezzanine::XML::Node& n) { Mezzanine::XML::Node nc = n; }, so const-correctness here mainly provides additional documentation.
1093 /// \n \n
1094 /// @subsection XMLModifyingNodeData Setting Node Data
1095 ///As discussed before, nodes can have name and value, both of which are c-strings. Depending on node type, name or value may be absent. @ref Mezzanine::XML::NodeType "NodeDocument" nodes
1096 /// do not have a name or value, @ref Mezzanine::XML::NodeType "NodeElement" and @ref Mezzanine::XML::NodeType "NodeDeclaration" nodes always have a name but never have a value,
1097 /// @ref Mezzanine::XML::NodeType "NodePcdata", @ref Mezzanine::XML::NodeType "NodeCdata", @ref Mezzanine::XML::NodeType "NodeComment" and @ref Mezzanine::XML::NodeType "NodeDocType" nodes never have a
1098 /// name but always have a value (it may be empty though), @ref Mezzanine::XML::NodeType "NodePi" nodes always have a name and a value (again, value may be empty). In order to set node's
1099 /// name or value, you can use the following functions:
1100 /// @code
1101 /// bool Mezzanine::XML::Node::SetName(const char_t* rhs);
1102 /// bool Mezzanine::XML::Node::SetName(const String& rhs);
1103 /// bool Mezzanine::XML::Node::SetValue(const char_t* rhs);
1104 /// @endcode
1105 /// Both functions try to set the name/value to the specified string, and return the operation result. The operation fails if the node can not have name or value (for instance, when
1106 /// trying to call SetName on a @ref Mezzanine::XML::NodeType "NodePcdata" node), if the node handle is null, or if there is insufficient memory to handle the request. The provided string
1107 /// is copied into document managed memory and can be destroyed after the function returns (for example, you can safely pass stack-allocated buffers to these functions). The name/value
1108 /// content is not verified, so take care to use only valid XML names, or the document may become malformed.
1109 /// \n \n
1110 /// There is no equivalent of ChildValue function for modifying text children of the node.
1111 /// \n \n
1112 /// This is an example of setting node name and value:
1113 /// @code
1114 /// Mezzanine::XML::Node node = doc.GetChild("node");
1115 ///
1116 /// // change node name
1117 /// std::cout << node.SetName("notnode");
1118 /// std::cout << ", new node name: " << node.Name() << std::endl;
1119 ///
1120 /// // change comment text
1121 /// std::cout << doc.GetLastChild().SetValue("useless comment");
1122 /// std::cout << ", new comment text: " << doc.LastChild().Value() << std::endl;
1123 ///
1124 /// // we can't change value of the element or name of the comment
1125 /// std::cout << node.SetValue("1") << ", " << doc.LastChild().SetName("2") << std::endl;
1126 /// @endcode
1127 /// @subsection XMLModifyingAttributeData Setting Attribute Data
1128 /// All attributes have name and value, both of which are strings (value may be empty). You can set them with the following functions:
1129 /// @code
1130 /// bool Mezzanine::XML::Attribute::SetName(const char_t* rhs);
1131 /// bool Mezzanine::XML::Attribute::SetValue(const char_t* rhs);
1132 /// @endcode
1133 /// Both functions try to set the name/value to the specified string, and return the operation result. The operation fails if the attribute handle is null, or if there is insufficient
1134 /// memory to handle the request. The provided string is copied into document managed memory and can be destroyed after the function returns (for example, you can safely pass
1135 /// stack-allocated buffers to these functions). The name/value content is not verified, so take care to use only valid XML names, or the document may become malformed.
1136 /// \n \n
1137 /// In addition to string functions, several functions are provided for handling attributes with numbers and booleans as values:
1138 /// @code
1139 /// bool Mezzanine::XML::Attribute::SetValue(int rhs);
1140 /// bool Mezzanine::XML::Attribute::SetValue(unsigned int rhs);
1141 /// bool Mezzanine::XML::Attribute::SetValue(double rhs);
1142 /// bool Mezzanine::XML::Attribute::SetValue(bool rhs);
1143 /// @endcode
1144 /// The above functions convert the argument to string and then call the base SetValue function. Integers are converted to a decimal form, floating-point numbers are converted to either
1145 /// decimal or scientific form, depending on the number magnitude, boolean values are converted to either "true" or "false".
1146 /// @warning Number conversion functions depend on current C locale as set with setlocale, so may generate unexpected results if the locale is different from "C".
1147 ///
1148 /// @note There are no portable 64-bit types in C++, so there is no corresponding SetValue function. If your platform has a 64-bit integer, you can easily write such a function yourself.
1149 ///
1150 /// For convenience, all set_value functions have the corresponding assignment operators:
1151 /// @code
1152 /// Mezzanine::XML::Attribute& Mezzanine::XML::Attribute::operator=(const char_t* rhs);
1153 /// Mezzanine::XML::Attribute& Mezzanine::XML::Attribute::operator=(int rhs);
1154 /// Mezzanine::XML::Attribute& Mezzanine::XML::Attribute::operator=(unsigned int rhs);
1155 /// Mezzanine::XML::Attribute& Mezzanine::XML::Attribute::operator=(double rhs);
1156 /// Mezzanine::XML::Attribute& Mezzanine::XML::Attribute::operator=(bool rhs);
1157 /// @endcode
1158 /// These operators simply call the right SetValue function and return the attribute they're called on; the return value of SetValue is ignored, so errors are ignored.
1159 /// \n \n
1160 /// This is an example of setting attribute name and value:
1161 /// @code
1162 /// Mezzanine::XML::Attribute attr = node.GetAttribute("id");
1163 ///
1164 /// // change attribute name/value
1165 /// std::cout << attr.SetName("key") << ", " << attr.SetValue("345");
1166 /// std::cout << ", new attribute: " << attr.name() << "=" << attr.value() << std::endl;
1167 ///
1168 /// // we can use numbers or booleans
1169 /// attr.SetValue(1.234);
1170 /// std::cout << "new attribute value: " << attr.Value() << std::endl;
1171 ///
1172 /// // we can also use assignment operators for more concise code
1173 /// attr = true;
1174 /// std::cout << "final attribute value: " << attr.value() << std::endl;
1175 /// @endcode
1176 /// @subsection XMLModifyingAdding Adding Nodes/Attributes
1177 /// Nodes and attributes do not exist without a document tree, so you can't create them without adding them to some document. A node or attribute can be created at the end of
1178 /// node/attribute list or before/after some other node:
1179 /// @code
1180 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::AppendAttribute(const char_t* Name);
1181 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::AppendAttribute(const String& Name);
1182 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::PrependAttribute(const char_t* Name);
1183 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::InsertAttributeAfter(const char_t* Name, const Mezzanine::XML::Attribute& attr);
1184 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::InsertAttributeBefore(const char_t* Name, const Mezzanine::XML::Attribute& attr);
1185 ///
1186 /// Mezzanine::XML::Node Mezzanine::XML::Node::AppendChild(Mezzanine::XML::NodeType type = NodeElement);
1187 /// Mezzanine::XML::Node Mezzanine::XML::Node::PrependChild(Mezzanine::XML::NodeType type = NodeElement);
1188 /// Mezzanine::XML::Node Mezzanine::XML::Node::InsertChildAfter(Mezzanine::XML::NodeType type, const Mezzanine::XML::Node& node);
1189 /// Mezzanine::XML::Node Mezzanine::XML::Node::InsertChildBefore(Mezzanine::XML::NodeType type, const Mezzanine::XML::Node& node);
1190 ///
1191 /// Mezzanine::XML::Node Mezzanine::XML::Node::AppendChild(const char_t* Name);
1192 /// Mezzanine::XML::Node Mezzanine::XML::Node::AppendChild(const String& Name);
1193 /// Mezzanine::XML::Node Mezzanine::XML::Node::PrependChild(const char_t* Name);
1194 /// Mezzanine::XML::Node Mezzanine::XML::Node::PrependChild(const String& Name);
1195 /// Mezzanine::XML::Node Mezzanine::XML::Node::InsertChildAfter(const char_t* Name, const Mezzanine::XML::Node& node);
1196 /// Mezzanine::XML::Node Mezzanine::XML::Node::InsertChildBefore(const char_t* Name, const Mezzanine::XML::Node& node);
1197 /// @endcode
1198 /// AppendAttribute and AppendChild create a new node/attribute at the end of the corresponding list of the node the method is called on; PrependAttribute and PrependChild create a new
1199 /// node/attribute at the beginning of the list; InsertAttributeAfter, InsertAttributeBefore, InsertChildAfter and InsertAttributeBefore add the node/attribute before or after the
1200 /// specified node/attribute.
1201 /// \n \n
1202 /// The overloads of AppendChild and PrependChild that accept Mezzanine::String references convert it to a string, then call the version of the function that accepts a c-style string.
1203 /// \n \n
1204 /// Attribute functions create an attribute with the specified name; you can specify the empty name and change the name later if you want to. Node functions with the type argument
1205 /// create the node with the specified type; since node type can't be changed, you have to know the desired type beforehand. Also note that not all types can be added as children; see
1206 /// below for clarification. Node functions with the name argument create the element node (NodeElement) with the specified name.
1207 /// \n \n
1208 /// All functions return the handle to the created object on success, and null handle on failure. There are several reasons for failure:
1209 /// - Adding fails if the target node is null;
1210 /// - Only @ref Mezzanine::XML::NodeType "NodeType::NodeElement" nodes can contain attributes, so attribute adding fails if node is not an element;
1211 /// - Only @ref Mezzanine::XML::NodeType "NodeType::NodeDocument" and @ref Mezzanine::XML::NodeType "NodeType::NodeElement" nodes can contain children, so child node adding fails if the
1212 /// target node is not an element or a document;
1213 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeDocument" and @ref Mezzanine::XML::NodeType "NodeType::NodeNull" nodes can not be inserted as children, so passing
1214 /// @ref Mezzanine::XML::NodeType "NodeType::NodeDocument" or @ref Mezzanine::XML::NodeType "NodeType::NodeNull value as type results in operation failure;
1215 /// - @ref Mezzanine::XML::NodeType "NodeType::NodeDeclaration" nodes can only be added as children of the document node; attempt to insert declaration node as a child of an element node fails;
1216 /// - Adding node/attribute results in memory allocation, which may fail;
1217 /// - Insertion functions fail if the specified node or attribute is null or is not in the target node's children/attribute list.
1218 ///
1219 /// Even if the operation fails, the document remains in consistent state, but the requested node/attribute is not added.
1220 /// @warning GetAttribute() and GetChild() functions do not add attributes or nodes to the tree, so code like node.GetAttribute("id") = 123; will not do anything if node does not
1221 /// have an attribute with name "id". Make sure you're operating with existing attributes/nodes by adding them if necessary.
1222 ///
1223 /// This is an example of adding new attributes/nodes to the document:
1224 /// @code
1225 /// // add node with some name
1226 /// Mezzanine::XML::Node node = doc.AppendChild("node");
1227 ///
1228 /// // add description node with text child
1229 /// Mezzanine::XML::Node descr = node.AppendChild("description");
1230 /// descr.AppendChild(Mezzanine::XML::NodePcdata).SetValue("Simple node");
1231 ///
1232 /// // add param node before the description
1233 /// Mezzanine::XML::Node param = node.InsertChildBefore("param", descr);
1234 ///
1235 /// // add attributes to param node
1236 /// param.AppendAttribute("name") = "version";
1237 /// param.AppendAttribute("value") = 1.1;
1238 /// param.InsertAttributeAfter("type", param.GetAttribute("name")) = "float";
1239 /// @endcode
1240 /// @subsection XMLModifyingRemoving Removing Nodes/Attributes
1241 /// If you do not want your document to contain some node or attribute, you can remove it with one of the following functions:
1242 /// @code
1243 /// bool Mezzanine::XML::Node::RemoveAttribute(const Mezzanine::XML::Attribute& a);
1244 /// bool Mezzanine::XML::Node::RemoveChild(const Mezzanine::XML::Node& n);
1245 /// @endcode
1246 /// RemoveAttribute removes the attribute from the attribute list of the node, and returns the operation result. RemoveChild removes the child node with the entire subtree (including
1247 /// all descendant nodes and attributes) from the document, and returns the operation result. Removing fails if one of the following is true:
1248 /// - The node the function is called on is null;
1249 /// - The attribute/node to be removed is null;
1250 /// - The attribute/node to be removed is not in the node's attribute/child list.
1251 ///
1252 /// Removing the attribute or node invalidates all handles to the same underlying object, and also invalidates all iterators pointing to the same object. Removing node also invalidates
1253 /// all past-the-end iterators to its attribute or child node list. Be careful to ensure that all such handles and iterators either do not exist or are not used after the attribute/node
1254 /// is removed.
1255 /// \n \n
1256 /// If you want to remove the attribute or child node by its name, two additional helper functions are available:
1257 /// @code
1258 /// bool Mezzanine::XML::Node::RemoveAttribute(const char_t* Name);
1259 /// bool Mezzanine::XML::Node::RemoveChild(const char_t* Name);
1260 /// @endcode
1261 /// These functions look for the first attribute or child with the specified name, and then remove it, returning the result. If there is no attribute or child with such name, the
1262 /// function returns false; if there are two nodes with the given name, only the first node is deleted. If you want to delete all nodes with the specified name, you can use code
1263 /// like this: while (node.RemoveChild("tool")) ;.
1264 /// \n \n
1265 /// This is an example of removing attributes/nodes from the document:
1266 /// @code
1267 /// // remove description node with the whole subtree
1268 /// Mezzanine::XML::Node node = doc.GetChild("node");
1269 /// node.RemoveChild("description");
1270 ///
1271 /// // remove id attribute
1272 /// Mezzanine::XML::Node param = node.GetChild("param");
1273 /// param.RemoveAttribute("value");
1274 ///
1275 /// // we can also remove nodes/attributes by handles
1276 /// Mezzanine::XML::Attribute id = param.GetAttribute("name");
1277 /// param.RemoveAttribute(id);
1278 /// @endcode
1279 /// @subsection XMLModifyingCloning Cloning Nodes/Attributes
1280 /// With the help of previously described functions, it is possible to create trees with any contents and structure, including cloning the existing data. However since this is an often
1281 /// needed operation, Mezzanine::xml provides built-in node/attribute cloning facilities. Since nodes and attributes do not exist without a document tree, you can't create a standalone copy
1282 /// - you have to immediately insert it somewhere in the tree. For this, you can use one of the following functions:
1283 /// @code
1284 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::AppendCopy(const Mezzanine::XML::Attribute& proto);
1285 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::PrependCopy(const Mezzanine::XML::Attribute& proto);
1286 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::InsertCopyAfter(const Mezzanine::XML::Attribute& proto, const Mezzanine::XML::Attribute& attr);
1287 /// Mezzanine::XML::Attribute Mezzanine::XML::Node::InsertCopyAfter(const Mezzanine::XML::Attribute& proto, const Mezzanine::XML::Attribute& attr);
1288 ///
1289 /// Mezzanine::XML::Node Mezzanine::XML::Node::AppendCopy(const Mezzanine::XML::Node& proto);
1290 /// Mezzanine::XML::Node Mezzanine::XML::Node::PrependCopy(const Mezzanine::XML::Node& proto);
1291 /// Mezzanine::XML::Node Mezzanine::XML::Node::InsertCopyAfter(const Mezzanine::XML::Node& proto, const Mezzanine::XML::Node& node);
1292 /// Mezzanine::XML::Node Mezzanine::XML::Node::InsertCopyAfter(const Mezzanine::XML::Node& proto, const Mezzanine::XML::Node& node);
1293 /// @endcode
1294 ///
1295 /// These functions mirror the structure of AppendChild, PrependChild, InsertChildBefore and related functions - they take the handle to the prototype object, which is to be cloned,
1296 /// insert a new attribute/node at the appropriate place, and then copy the attribute data or the whole node subtree to the new object. The functions return the handle to the resulting
1297 /// duplicate object, or null handle on failure.
1298 /// \n \n
1299 /// The attribute is copied along with the name and value; the node is copied along with its type, name and value; additionally attribute list and all children are recursively cloned,
1300 /// resulting in the deep subtree clone. The prototype object can be a part of the same document, or a part of any other document.
1301 /// \n \n
1302 /// The failure conditions resemble those of AppendChild, InsertChild_before and related functions, consult their documentation for more information. There are additional caveats
1303 /// specific to cloning functions:
1304 /// - Cloning null handles results in operation failure;
1305 /// - Node cloning starts with insertion of the node of the same type as that of the prototype; for this reason, cloning functions can not be directly used to clone entire
1306 /// documents, since @ref Mezzanine::XML::NodeType "NodeType::NodeDocument" is not a valid insertion type. The example below provides a workaround.
1307 /// - It is possible to copy a subtree as a child of some node inside this subtree, i.e. node.AppendCopy(node.GetParent().GetParent());. This is a valid operation, and it results
1308 /// in a clone of the subtree in the state before cloning started, i.e. no infinite recursion takes place.
1309 ///
1310 /// This is an example with one possible implementation of include tags in XML. It illustrates node cloning and usage of other document modification functions:
1311 /// @code
1312 /// bool LoadPreprocess(Mezzanine::XML::Document& doc, const char* path);
1313 ///
1314 /// bool PreProcess(Mezzanine::XML::Node node)
1315 /// {
1316 /// for (Mezzanine::XML::Node child = node.GetFirstChild(); child; )
1317 /// {
1318 /// if (child.Type() == Mezzanine::XML::NodePi && strcmp(child.Name(), "include") == 0)
1319 /// {
1320 /// Mezzanine::XML::Node include = child;
1321 ///
1322 /// // load new preprocessed document (note: ideally this should handle relative paths)
1323 /// const char* path = include.Value();
1324 ///
1325 /// Mezzanine::XML::Document doc;
1326 /// if (!LoadPreprocess(doc, path)) return false;
1327 ///
1328 /// // insert the comment marker above include directive
1329 /// node.InsertChildBefore(pugi::NodeComment, include).SetValue(path);
1330 ///
1331 /// // copy the document above the include directive (this retains the original order!)
1332 /// for (Mezzanine::XML::Node ic = doc.FirstChild(); ic; ic = ic.NextSibling())
1333 /// {
1334 /// node.InsertCopyAfter(ic, include);
1335 /// }
1336 ///
1337 /// // remove the include node and move to the next child
1338 /// child = child.NextSibling();
1339 ///
1340 /// node.RemoveChild(include);
1341 /// }
1342 /// else
1343 /// {
1344 /// if (!PreProcess(child)) return false;
1345 ///
1346 /// child = child.NextSibling();
1347 /// }
1348 /// }
1349 ///
1350 /// return true;
1351 /// }
1352 ///
1353 /// bool LoadPreprocess(Mezzanine::XML::Document& doc, const char* path)
1354 /// {
1355 /// Mezzanine::XML::ParseResult result = doc.LoadFile(path, Mezzanine::XML::ParseDefault | Mezzanine::XML::ParsePi); // for <?include?>
1356 ///
1357 /// return result ? PreProcess(doc) : false;
1358 /// }
1359 /// @endcode
1360 /// @section XMLSaving Saving Documents
1361 /// - @ref XMLSavingFile
1362 /// - @ref XMLSavingStreams
1363 /// - @ref XMLSavingWriter
1364 /// - @ref XMLSavingSubtree
1365 /// - @ref XMLSavingOptions
1366 /// - @ref XMLSavingEncodings
1367 ///
1368 /// Often after creating a new document or loading the existing one and processing it, it is necessary to save the result back to file. Also it is occasionally useful to output the
1369 /// whole document or a subtree to some stream; use cases include debug printing, serialization via network or other text-oriented medium, etc. Mezzanine::xml provides several functions
1370 /// to output any subtree of the document to a file, stream or another generic transport interface; these functions allow one to customize the output format ( see @ref XMLSavingOptions ), and
1371 /// also perform necessary encoding conversions ( see @ref XMLSavingEncodings ). This section documents the relevant functionality.
1372 /// \n \n
1373 /// Before writing to the destination the node/attribute data is properly formatted according to the node type; all special XML symbols, such as < and \&, are properly escaped. In
1374 /// order to guard against forgotten node/attribute names, empty node/attribute names are printed as ":anonymous". For well-formed output, make sure all node and attribute names are
1375 /// set to meaningful values.
1376 /// \n \n
1377 /// CDATA sections with values that contain "]]>" are split into several sections as follows: section with value "pre]]>post" is written as <![CDATA[pre]]]]><![CDATA[>post]]>. While
1378 /// this alters the structure of the document (if you load the document after saving it, there will be two CDATA sections instead of one), this is the only way to escape CDATA contents.
1379 /// @subsection XMLSavingFile Saving Documents to Files
1380 /// If you want to save the whole document to a file, you can use one of the following functions:
1381 /// @code
1382 /// bool Mezzanine::XML::Document::SaveFile(const char* Path, const Mezzanine::XML::char_t* indent = "\t", unsigned int flags = Mezzanine::XML::FormatDefault, Mezzanine::XML::Encoding encoding = EncodingAuto) const;
1383 /// bool Mezzanine::XML::Document::SaveFile(const wchar_t* Path, const Mezzanine::XML::char_t* indent = "\t", unsigned int flags = Mezzanine::XML::FormatDefault, Mezzanine::XML::Encoding encoding = EncodingAuto) const;
1384 /// @endcode
1385 /// These functions accept file path as its first argument, and also three optional arguments, which specify indentation and other output options (see Output options) and output data
1386 /// encoding ( see @ ref XMLSavingEncodings ). The Path has the target operating system format, so it can be a relative or absolute one, it should have the delimiters of the target
1387 /// system, it should have the exact case if the target file system is case-sensitive, etc.
1388 /// \n \n
1389 /// File path is passed to the system file opening function as is in case of the first function (which accepts const char* Path); the second function either uses a special file opening
1390 /// function if it is provided by the runtime library or converts the path to UTF-8 and uses the system file opening function.
1391 /// \n \n
1392 /// SaveFile opens the target file for writing, outputs the requested header (by default a document declaration is output, unless the document already has one), and then saves the
1393 /// document contents. If the file could not be opened, the function returns false. Calling SaveFile is equivalent to creating an Mezzanine::XML::WriterFile object with FILE* handle as the
1394 /// only constructor argument and then calling save; see @ref XMLSavingWriter for writer interface details.
1395 /// \n \n
1396 /// This is a simple example of saving XML document to a file :
1397 /// @code
1398 /// // save document to file
1399 /// std::cout << "Saving result: " << doc.SaveFile("save_file_output.xml") << std::endl;
1400 /// @endcode
1401 /// @subsection XMLSavingStreams Saving Documents to C++ IOstreams
1402 /// To enhance interoperability Mezzanine::xml provides functions for saving document to any object which implements C++ std::ostream interface. This allows you to save documents to any
1403 /// standard C++ stream (i.e. file stream) or any third-party compliant implementation (i.e. Boost Iostreams). Most notably, this allows for easy debug output, since you can use
1404 /// std::cout stream as saving target. There are two functions, one works with narrow character streams, another handles wide character ones:
1405 /// @code
1406 /// void Mezzanine::XML::Document::Save(std::ostream& stream, const char_t* indent = "\t", unsigned int flags = Mezzanine::XML::FormatDefault, Mezzanine::XML::Encoding encoding = EncodingAuto) const;
1407 /// void Mezzanine::XML::Document::Save(std::wostream& stream, const char_t* indent = "\t", unsigned int flags = Mezzanine::XML::FormatDefault) const;
1408 /// @endcode
1409 /// Calling Save with an std::ostream argument saves the document to the stream in the same way as SaveFile (i.e. with requested header and with encoding conversions). On the other
1410 /// hand, save with std::wstream argument saves the document to the wide stream with @ref Mezzanine::XML::Encoding "Encoding::Encodingwchar_t" encoding. Because of this, using save with wide
1411 /// character streams requires careful (usually platform-specific) stream setup (i.e. using the imbue function). Generally use of wide streams is discouraged, however it provides you
1412 /// with the ability to save documents to non-Unicode encodings, i.e. you can save Shift-JIS encoded data if you set the correct locale.
1413 /// \n \n
1414 /// Calling Save with stream target is equivalent to creating an Mezzanine::XML::WriterStream object with stream as the only constructor argument and then calling save; see
1415 /// @ref XMLSavingWriter for writer interface details.
1416 /// \n \n
1417 /// This is a simple example of saving XML document to standard output:
1418 /// @code
1419 /// // save document to standard output
1420 /// std::cout << "Document:\n";
1421 /// doc.Save(std::cout);
1422 /// @endcode
1423 /// @subsection XMLSavingWriter Saving Document via Writer Interface
1424 /// All of the above saving functions are implemented in terms of the Mezzanine::XML::Writer interface. This is a simple interface with a single function, which is called several times
1425 /// during output process with chunks of document data as input.
1426 /// @code
1427 /// class Writer
1428 /// {
1429 /// public:
1430 /// virtual void Write(const void* data, size_t size) = 0;
1431 /// };
1432 ///
1433 /// void Mezzanine::XML::Document::Save (Writer &WriterInstance, const char_t *indent="\t", unsigned int flags=FormatDefault, Encoding DocumentEncoding=EncodingAuto) const;
1434 /// @endcode
1435 /// In order to output the document via some custom transport, for example sockets, you should create an object which implements Mezzanine::XML::Writer interface and pass it to save function.
1436 /// Mezzanine::XML::Writer::Write function is called with a buffer as an input, where data points to buffer start, and size is equal to the buffer size in bytes. The Write implementation must
1437 /// write the buffer to the transport; it can not save the passed buffer pointer, as the buffer contents will change after write returns. The buffer contains the chunk of document data
1438 /// in the desired encoding.
1439 /// \n \n
1440 /// The Write function is called with relatively large blocks (size is usually several kilobytes, except for the first block with BOM, which is output only if Mezzanine::XML::FormatWriteBom
1441 /// is set, and last block, which may be small), so there is often no need for additional buffering in the implementation.
1442 /// \n \n
1443 /// This is a simple example of custom writer for saving document data to STL string:
1444 /// @code
1445 /// struct StringWriter: Mezzanine::XML::Writer
1446 /// {
1447 /// std::string Result;
1448 ///
1449 /// virtual void Write(const void* data, size_t size)
1450 /// {
1451 /// Result += std::string(static_cast<const char*>(data), size);
1452 /// }
1453 /// };
1454 /// @endcode
1455 /// @subsection XMLSavingSubtree Saving a Single Subtree
1456 /// While the previously described functions save the whole document to the destination, it is easy to save a single subtree. The following functions are provided:
1457 /// @code
1458 /// void Mezzanine::XML::Node::Print(std::basic_ostream< char, std::char_traits< char > > &os, const char_t *indent="\t", unsigned int flags=FormatDefault, Encoding DocumentEncoding=EncodingAuto, unsigned int Depth=0) const ;
1459 /// void Mezzanine::XML::Node::Print(std::basic_ostream< wchar_t, std::char_traits< wchar_t > > &os, const char_t *indent="\t", unsigned int flags=FormatDefault, unsigned int Depth=0) const ) const;
1460 /// void Mezzanine::XML::Node::Print(Mezzanine::XML::Writer &WriterInstance, const char_t *indent="\t", unsigned int flags=FormatDefault, Encoding DocumentEncoding=EncodingAuto, unsigned int Depth=0) const;
1461 /// @endcode
1462 /// These functions have the same arguments with the same meaning as the corresponding Mezzanine::XML::Document::Save functions, and allow you to save the subtree to either a C++ IOstream
1463 /// or to any object that implements Mezzanine::XML::Writer interface.
1464 /// \n \n
1465 /// Saving a subtree differs from saving the whole document: the process behaves as if Mezzanine::XML::FormatWriteBom is off, and Mezzanine::XML::FormatNoDeclaration is on, even if actual values
1466 /// of the flags are different. This means that BOM is not written to the destination, and document declaration is only written if it is the node itself or is one of node's children.
1467 /// Note that this also holds if you're saving a document; this example illustrates the difference:
1468 /// @code
1469 /// // get a test document
1470 /// Mezzanine::XML::Document doc;
1471 /// doc.Load("<foo bar='baz'><call>hey</call></foo>");
1472 ///
1473 /// // print document to standard output (prints <?xml version="1.0"?><foo bar="baz"><call>hey</call></foo>)
1474 /// doc.Save(std::cout, "", Mezzanine::XML::FormatRaw);
1475 /// std::cout << std::endl;
1476 ///
1477 /// // print document to standard output as a regular node (prints <foo bar="baz"><call>hey</call></foo>)
1478 /// doc.Print(std::cout, "", Mezzanine::XML::FormatRaw);
1479 /// std::cout << std::endl;
1480 ///
1481 /// // print a subtree to standard output (prints <call>hey</call>)
1482 /// doc.GetChild("foo").GetChild("call").Print(std::cout, "", Mezzanine::XML::FormatRaw);
1483 /// std::cout << std::endl;
1484 /// @endcode
1485 /// @subsection XMLSavingOptions Output Options
1486 /// All saving functions accept the optional parameter flags. This is a bitmask that customizes the output format; you can select the way the document nodes are printed and select the
1487 /// needed additional information that is output before the document contents.
1488 /// @note You should use the usual bitwise arithmetics to manipulate the bitmask: to enable a flag, use mask | flag; to disable a flag, use mask & ~flag.
1489 ///
1490 /// These flags control the resulting tree contents:
1491 /// - Mezzanine::XML::FormatIndent determines if all nodes should be indented with the indentation string (this is an additional parameter for all saving functions, and is "\t" by - default).
1492 /// If this flag is on, before every node the indentation string is output several times, where the amount of indentation depends on the node's depth relative to the
1493 /// output subtree. This flag has no effect if Mezzanine::XML::FormatRaw is enabled. This flag is off by default.
1494 /// - Mezzanine::XML::FormatRaw switches between formatted and raw output. If this flag is on, the nodes are not indented in any way, and also no newlines that are not part of
1495 /// document text are printed. Raw mode can be used for serialization where the result is not intended to be read by humans; also it can be useful if the document was parsed
1496 /// with Mezzanine::XML::ParseWsPcdata flag, to preserve the original document formatting as much as possible. This flag is on by default.
1497 ///
1498 ///These flags control the additional output information:
1499 /// - Mezzanine::XML::FormatNoDeclaration disables default node declaration output. By default, if the document is saved via save or SaveFile function, and it does not have any
1500 /// document declaration, a default declaration is output before the document contents. Enabling this flag disables this declaration. This flag has no effect in
1501 /// Mezzanine::XML::Node::Print functions: they never output the default declaration. This flag is off by default.
1502 /// - Mezzanine::XML::FormatWriteBom enables Byte Order Mark (BOM) output. By default, no BOM is output, so in case of non UTF-8 encodings the resulting document's encoding may not
1503 /// be recognized by some parsers and text editors, if they do not implement sophisticated encoding detection. Enabling this flag adds an encoding-specific BOM to the output. This
1504 /// flag has no effect in Mezzanine::XML::Node::Print functions: they never output the BOM. This flag is off by default.
1505 ///
1506 /// Additionally, there is one predefined option mask:
1507 /// - Mezzanine::XML::FormatDefault is the default set of flags, i.e. it has all options set to their default values. This differs from the default pugixml settings and only sets
1508 /// Mezzanine::XML::FormatRaw . This is to minimize output size, and optimize for computer consumption of xml.
1509 ///
1510 /// @subsection XMLSavingEncodings Encodings
1511 /// Mezzanine::xml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little endian), UTF-32 (big and little endian); UCS-2 is naturally supported since it's a strict subset
1512 /// of UTF-16) and handles all encoding conversions during output. The output encoding is set via the encoding parameter of saving functions, which is of type xml_encoding. The
1513 /// possible values for the encoding are documented in Encodings; the only flag that has a different meaning is EncodingAuto.
1514 /// \n \n
1515 /// While all other flags set the exact encoding, EncodingAuto is meant for automatic encoding detection. The automatic detection does not make sense for output encoding, since there
1516 /// is usually nothing to infer the actual encoding from, so here @ref Mezzanine::XML::Encoding "EncodingAuto" means UTF-8 encoding, which is the most popular encoding for XML data storage. This is also the default
1517 /// value of output encoding; specify another value if you do not want UTF-8 encoded output.
1518 /// \n \n
1519 /// Also note that wide stream saving functions do not have encoding argument and always assume @ref Mezzanine::XML::Encoding "Encodingwchar_t" encoding.
1520 /// @note The current behavior for Unicode conversion is to skip all invalid UTF sequences during conversion. This behavior should not be relied upon; if your node/attribute names do
1521 /// not contain any valid UTF sequences, they may be output as if they are empty, which will result in malformed XML document.
1522 /// @section XMLXPath XPath
1523 /// - @ref XMLXPathTypes
1524 /// - @ref XMLXPathSelecting
1525 /// - @ref XMLXPathQuery
1526 /// - @ref XMLXPathVariables
1527 /// - @ref XMLXPathError
1528 /// - @ref XMLXPathStandards
1529 ///
1530 /// If the task at hand is to select a subset of document nodes that match some criteria, it is possible to code a function using the existing traversal functionality for any practical
1531 /// criteria. However, often either a data-driven approach is desirable, in case the criteria are not predefined and come from a file, or it is inconvenient to use traversal interfaces
1532 /// and a higher-level Domain Specific Language is required. There is a standard language for XML processing, XPath, that can be useful for these cases. Mezzanine::xml implements an almost
1533 /// complete subset of XPath 1.0. Because of differences in document object model and some performance implications, there are minor violations of the official specifications, which
1534 /// can be found in @ref XMLXPathStandards . The rest of this section describes the interface for XPath functionality. Please note that if you wish to learn to use XPath language, you
1535 /// have to look for other tutorials or manuals.
1536 /// \n \n
1537 /// @subsection XMLXPathTypes XPath Types
1538 /// Each XPath expression can have one of the following types: boolean, number, string or node set. Boolean type corresponds to bool type, number type corresponds to double type, string
1539 /// type corresponds to either std::string or std::wstring, depending on whether wide character interface is enabled, and node set corresponds to Mezzanine::XML::XPathNodeSet type. There is
1540 /// an enumeration, Mezzanine::XML::XPathValueType, which can take the values @ref Mezzanine::XML::XPathValueType "XPathTypeBoolean", @ref Mezzanine::XML::XPathValueType "XPathTypeNumber",
1541 /// @ref Mezzanine::XML::XPathValueType XPathTypeString or @ref Mezzanine::XML::XPathValueType XPathTypeNodeSet, accordingly.
1542 /// \n \n
1543 /// Because an XPath node can be either a node or an attribute, there is a special type, Mezzanine::XML::XPathNode, which is a discriminated union of these types. A value of this type
1544 /// contains two node handles, one of Mezzanine::XML::Node type, and another one of Mezzanine::XML::Attribute type; at most one of them can be non-null. The accessors to get these handles are
1545 /// available:
1546 /// @code
1547 /// Mezzanine::XML::Node Mezzanine::XML::XPathNode::GetNode() const;
1548 /// Mezzanine::XML::Attribute Mezzanine::XML::XPathNode::GetAttribute() const;
1549 /// @endcode
1550 /// XPath nodes can be null, in which case both accessors return null handles.
1551 /// \n \n
1552 /// Note that as per XPath specification, each XPath node has a parent, which can be retrieved via this function:
1553 /// @code
1554 /// Mezzanine::XML::Node Mezzanine::XML::XPathNode::GetParent() const;
1555 /// @endcode
1556 /// The GetParent function returns the node's parent if the XPath node corresponds to Mezzanine::XML::Node handle (equivalent to GetNode().GetParent()), or the node to which the attribute
1557 /// belongs to, if the XPath node corresponds to Mezzanine::XML::Attribute handle. For null nodes, parent returns null handle.
1558 /// \n \n
1559 /// Like node and attribute handles, XPath node handles can be implicitly cast to boolean-like object to check if it is a null node, and also can be compared for equality with
1560 /// each other.
1561 /// \n \n
1562 /// You can also create XPath nodes with one of the three constructors: the default constructor, the constructor that takes node argument, and the constructor that takes an attribute
1563 /// and a node argument (in which case the attribute must belong to the attribute list of the node). The constructor from Mezzanine::XML::Node is implicit, so you can usually pass
1564 /// Mezzanine::XML::Node to functions that expect Mezzanine::XML::XPathNode. Apart from that you usually don't need to create your own XPath node objects, since they are returned to you via
1565 /// selection functions.
1566 /// \n \n
1567 /// XPath expressions operate not on single nodes, but instead on node sets. A node set is a collection of nodes, which can be optionally ordered in either a forward document order
1568 /// or a reverse one. Document order is defined in XPath specification; an XPath node is before another node in document order if it appears before it in XML representation of the
1569 /// corresponding document.
1570 /// \n \n
1571 /// Node sets are represented by Mezzanine::XML::XPathNodeSet object, which has an interface that resembles one of sequential random-access containers. It has an iterator type along with
1572 /// usual begin/past-the-end iterator accessors:
1573 /// @code
1574 /// typedef const Mezzanine::XML::XPathNode* Mezzanine::XML::XPathNodeSet::const_iterator;
1575 /// const_iterator Mezzanine::XML::XPathNodeSet::begin() const;
1576 /// const_iterator Mezzanine::XML::XPathNodeSet::end() const;
1577 /// @endcode
1578 /// And it also can be iterated via indices, just like std::vector:
1579 /// @code
1580 /// const Mezzanine::XML::XPathNode& Mezzanine::XML::XPathNodeSet::operator[](size_t index) const;
1581 /// size_t Mezzanine::XML::XPathNodeSet::size() const;
1582 /// bool Mezzanine::XML::XPathNodeSet::empty() const;
1583 /// @endcode
1584 /// All of the above operations have the same semantics as that of std::vector: the iterators are random-access, all of the above operations are constant time, and accessing the element
1585 /// at index that is greater or equal than the set size results in undefined behavior. You can use both iterator-based and index-based access for iteration, however the iterator-based
1586 /// one can be faster.
1587 /// \n \n
1588 /// The order of iteration depends on the order of nodes inside the set; the order can be queried via the following function:
1589 /// @code
1590 /// enum Mezzanine::XML::XPathNodeSet::CollectionType { TypeUnsorted, TypeSorted, TypeSortedReverse };
1591 /// CollectionType Mezzanine::XML::XPathNodeSet::Type() const;
1592 /// @endcode
1593 /// The Type function returns the current order of nodes; TypeSorted means that the nodes are in forward document order, TypeSortedReverse means that the nodes are in reverse document
1594 /// order, and TypeUnsorted means that neither order is guaranteed (nodes can accidentally be in a sorted order even if Type() returns TypeUnsorted). If you require a specific order of
1595 /// iteration, you can change it via sort function:
1596 /// void Mezzanine::XML::XPathNodeSet::sort(bool reverse = false);
1597 /// @warning When converted from the pugixml naming scheme, changes were made to this class conservatively. Once it is determine what the new names should be. this could be changed.
1598 ///
1599 /// Calling sort sorts the nodes in either forward or reverse document order, depending on the argument; after this call Type() will return TypeSorted or TypeSortedReverse.
1600 /// \n \n
1601 /// Often the actual iteration is not needed; instead, only the first element in document order is required. For this, a special accessor is provided:
1602 /// @code
1603 /// Mezzanine::XML::XPathNode Mezzanine::XML::XPathNodeSet::first() const;
1604 /// @endcode
1605 /// This function returns the first node in forward document order from the set, or null node if the set is empty. Note that while the result of the node does not depend on the order of
1606 /// nodes in the set (i.e. on the result of Type()), the complexity does - if the set is sorted, the complexity is constant, otherwise it is linear in the number of elements or worse.
1607 /// \n \n
1608 /// While in the majority of cases the node set is returned by XPath functions, sometimes there is a need to manually construct a node set. For such cases, a constructor is provided
1609 /// which takes an iterator range (const_iterator is a typedef for const Mezzanine::XML::XPathNode*), and an optional type:
1610 /// @code
1611 /// Mezzanine::XML::XPathNodeSet::XPathNodeSet(const_iterator begin, const_iterator end, CollectionType Type=TypeUnsorted);
1612 /// @endcode
1613 /// The constructor copies the specified range and sets the specified type. The objects in the range are not checked in any way; you'll have to ensure that the range contains no
1614 /// duplicates, and that the objects are sorted according to the type parameter. Otherwise XPath operations with this set may produce unexpected results.
1615 /// \n \n
1616 /// @subsection XMLXPathSelecting Selecting Nodes via XPath Expression
1617 /// If you want to select nodes that match some XPath expression, you can do it with the following functions:
1618 /// @code
1619 /// Mezzanine::XML::XPathNode Mezzanine::XML::Node::FindSingleNode(const char_t* query, XPathVariableSet* variables = 0) const;
1620 /// Mezzanine::XML::XPathNodeSet Mezzanine::XML::Node::FindNodes(const char_t* query, XPathVariableSet* variables = 0) const;
1621 /// @endcode
1622 /// The FindNodes function compiles the expression and then executes it with the node as a context node, and returns the resulting node set. FindSingleNode returns only the first node
1623 /// in document order from the result, and is equivalent to calling FindNodes(query).first(). If the XPath expression does not match anything, or the node handle is null, FindNodes
1624 /// returns an empty set, and FindSingleNode returns null XPath node.
1625 /// \n \n
1626 /// Both functions throw Mezzanine::XML::XPathException if the query can not be compiled or if it returns a value with type other than node set; see
1627 /// Error handling for details.
1628 /// \n \n
1629 /// While compiling expressions is fast, the compilation time can introduce a significant overhead if the same expression is used many times on small subtrees. If you're doing many
1630 /// similar queries, consider compiling them into query objects (see @ref XMLXPathQuery for further reference). Once you get a compiled query object, you can pass it to Find functions
1631 /// instead of an expression string:
1632 /// @code
1633 /// Mezzanine::XML::XPathNode Mezzanine::XML::Node::FindSingleNode(const Mezzanine::XML::XPathQuery& query) const;
1634 /// Mezzanine::XML::XPathNodeSet Mezzanine::XML::Node::FindNodes(const Mezzanine::XML::XPathQuery& query) const;
1635 /// @endcode
1636 /// Both functions throw Mezzanine::XML::XPathException if the query returns a value with type other than node set.
1637 /// \n \n
1638 /// This is an example of selecting nodes using XPath expressions:
1639 /// @code
1640 /// Mezzanine::XML::XPathNodeSet tools = doc.FindNodes("/Profile/Tools/Tool[@AllowRemote='true' and @DeriveCaptionFrom='lastparam']");
1641 ///
1642 /// std::cout << "Tools:";
1643 ///
1644 /// for (Mezzanine::XML::XPathNodeSet::const_iterator it = tools.begin(); it != tools.end(); ++it)
1645 /// {
1646 /// Mezzanine::XML::XPathNode node = *it;
1647 /// std::cout << " " << node.GetNode().GetAttribute("Filename").Value();
1648 /// }
1649 ///
1650 /// Mezzanine::XML::XPathNode BuildTool = doc.FindSingleNode("//Tool[contains(Description, 'build system')]");
1651 ///
1652 /// std::cout << "\nBuild tool: " << BuildTool.GetNode().GetAttribute("Filename").Value() << "\n";
1653 /// @endcode
1654 /// @subsection XMLXPathQuery Using Query Objects
1655 /// When you call FindNodes with an expression string as an argument, a query object is created behind the scenes. A query object represents a compiled XPath expression. Query objects
1656 /// can be useful in the following circumstances:
1657 /// - You can precompile expressions to query objects to save compilation time if it becomes an issue;
1658 /// - You can use query objects to evaluate XPath expressions which result in booleans, numbers or strings;
1659 /// - You can get the type of expression value via query object.
1660 ///
1661 /// Query objects correspond to Mezzanine::XML::XPathQuery type. They are immutable and non-copyable: they are bound to the expression at creation time and can not be cloned. If you want to
1662 /// put query objects in a container, allocate them on heap via new operator and store pointers to Mezzanine::XML::XPathQuery in the container.
1663 /// \n \n
1664 /// You can create a query object with the constructor that takes XPath expression as an argument:
1665 /// @code
1666 /// explicit Mezzanine::XML::XPathQuery::XPathQuery(const char_t* query, XPathVariableSet* variables = 0);
1667 /// @endcode
1668 /// The expression is compiled and the compiled representation is stored in the new query object. If compilation fails, XPathException is thrown if exception handling is not disabled
1669 /// (see @ref XMLXPathError for details). After the query is created, you can query the type of the evaluation result using the following function:
1670 /// @code
1671 /// Mezzanine::XML::XPathValueType Mezzanine::XML::XPathQuery::ReturnType() const;
1672 /// @endcode
1673 /// You can evaluate the query using one of the following functions:
1674 /// @code
1675 /// bool Mezzanine::XML::XPathQuery::EvaluateBoolean(const Mezzanine::XML::XPathNode& n) const;
1676 /// double Mezzanine::XML::XPathQuery::EvaluateNumber(const Mezzanine::XML::XPathNode& n) const;
1677 /// Mezzanine::String Mezzanine::XML::XPathQuery::EvaluateString(const Mezzanine::XML::XPathNode& n) const;
1678 /// Mezzanine::XML::XPathNodeSet Mezzanine::XML::XPathQuery::EvaluateNodeSet(const Mezzanine::XML::XPathNode& n) const;
1679 /// @endcode
1680 /// All functions take the context node as an argument, compute the expression and return the result, converted to the requested type. According to XPath specification, value of any
1681 /// type can be converted to boolean, number or string value, but no type other than node set can be converted to node set. Because of this, EvaluateBoolean, EvaluateNumber and
1682 /// EvaluateString always return a result, but EvaluateNodeSet results in an error if the return type is not node set ( see @ref XMLXPathError ).
1683 /// @note Calling node.FindNodes("query") is equivalent to calling Mezzanine::XML::XPathQuery("query").EvaluateNodeSet(node).
1684 ///
1685 /// There is another string evaluation
1686 /// function:
1687 /// @code
1688 /// size_t Mezzanine::XML::XPathQuery::EvaluateString(char_t* buffer, size_t capacity, const Mezzanine::XML::XPathNode& n) const;
1689 /// @endcode
1690 /// This function evaluates the string, and then writes the result to buffer (but at most capacity characters); then it returns the full size of the result in characters, including
1691 /// the terminating zero. If capacity is not 0, the resulting buffer is always zero-terminated. You can use this function as follows:
1692 /// - First call the function with buffer = 0 and capacity = 0; then allocate the returned amount of characters, and call the function again, passing the allocated storage and the
1693 /// amount of characters;
1694 /// - First call the function with small buffer and buffer capacity; then, if the result is larger than the capacity, the output has been trimmed, so allocate a larger buffer and
1695 /// call the function again.
1696 ///
1697 /// This is an example of using query objects:
1698 /// @code
1699 /// // Select nodes via compiled query
1700 /// Mezzanine::XML::XPathQuery QueryRemoteTools("/Profile/Tools/Tool[@AllowRemote='true']");
1701 ///
1702 /// Mezzanine::XML::XPathNodeSet tools = QueryRemoteTools.EvaluateNodeSet(doc);
1703 /// std::cout << "Remote tool: ";
1704 /// tools[2].node().print(std::cout);
1705 ///
1706 /// // Evaluate numbers via compiled query
1707 /// Mezzanine::XML::XPathQuery QueryTimeouts("sum(//Tool/@Timeout)");
1708 /// std::cout << QueryTimeouts.EvaluateNumber(doc) << std::endl;
1709 ///
1710 /// // Evaluate strings via compiled query for different context nodes
1711 /// Mezzanine::XML::XPathQuery QueryNameValid("string-length(substring-before(@Filename, '_')) > 0 and @OutputFileMasks");
1712 /// Mezzanine::XML::XPathQuery QueryName("concat(substring-before(@Filename, '_'), ' produces ', @OutputFileMasks)");
1713 ///
1714 /// for (Mezzanine::XML::Node tool = doc.FirstElementByPath("Profile/Tools/Tool"); tool; tool = tool.NextSibling())
1715 /// {
1716 /// std::string s = QueryName.EvaluateString(tool);
1717 ///
1718 /// if (QueryNameValid.EvaluateBoolean(tool)) std::cout << s << std::endl;
1719 /// }
1720 /// @endcode
1721 /// @subsection XMLXPathVariables Using Variables
1722 /// XPath queries may contain references to variables; this is useful if you want to use queries that depend on some dynamic parameter without manually preparing the complete query
1723 /// string, or if you want to reuse the same query object for similar queries.
1724 /// \n \n
1725 /// Variable references have the form $name; in order to use them, you have to provide a variable set, which includes all variables present in the query with correct types. This set
1726 /// is passed to Mezzanine::XML::XPathQuery constructor or to FindNodes/FindNode functions:
1727 /// @code
1728 /// explicit Mezzanine::XML::XPathQuery::Mezzanine::XML::XPathQuery(const char_t* query, XPathVariableSet* variables = 0);
1729 /// Mezzanine::XML::XPathNode xml_node::FindNode(const char_t* query, XPathVariableSet* variables = 0) const;
1730 /// XPathNodeSet xml_node::FindNodes(const char_t* query, XPathVariableSet* variables = 0) const;
1731 /// @endcode
1732 /// If you're using query objects, you can change the variable values before evaluate/select calls to change the query behavior.
1733 /// @note The variable set pointer is stored in the query object; you have to ensure that the lifetime of the set exceeds that of query object.
1734 ///
1735 /// Variable sets correspond to XPathVariableSet type, which is essentially a variable container.
1736 /// \n \n
1737 /// You can add new variables with the following function:
1738 /// @code
1739 /// Mezzanine::XML::XPathVariable* Mezzanine::XML::XPathVariableSet::Add(const char_t* Name, Mezzanine::XML::XPathValueType type);
1740 /// @endcode
1741 /// The function tries to add a new variable with the specified name and type; if the variable with such name does not exist in the set, the function adds a new variable and returns
1742 /// the variable handle; if there is already a variable with the specified name, the function returns the variable handle if variable has the specified type. Otherwise the function
1743 /// returns null pointer; it also returns null pointer on allocation failure.
1744 /// \n \n
1745 /// New variables are assigned the default value which depends on the type: 0 for numbers, false for booleans, empty string for strings and empty set for node sets.
1746 /// \n \n
1747 /// You can get the existing variables with the following functions:
1748 /// @code
1749 /// XPathVariable* XPathVariableSet::Get(const char_t* Name);
1750 /// const XPathVariable* XPathVariableSet::Get(const char_t* Name) const;
1751 /// @endcode
1752 /// The functions return the variable handle, or null pointer if the variable with the specified name is not found.
1753 /// \n \n
1754 /// Additionally, there are the helper functions for setting the variable value by name; they try to add the variable with the corresponding type, if it does not exist, and to set the
1755 /// value. If the variable with the same name but with different type is already present, they return false; they also return false on allocation failure. Note that these functions do
1756 /// not perform any type conversions.
1757 /// @code
1758 /// bool XPathVariableSet::Set(const char_t* Name, bool Value);
1759 /// bool XPathVariableSet::Set(const char_t* Name, double Value);
1760 /// bool XPathVariableSet::Set(const char_t* Name, const char_t* Value);
1761 /// bool XPathVariableSet::Set(const char_t* Name, const XPathNodeSet& Value);
1762 /// @endcode
1763 /// The variable values are copied to the internal variable storage, so you can modify or destroy them after the functions return.
1764 /// \n \n
1765 /// If setting variables by name is not efficient enough, or if you have to inspect variable information or get variable values, you can use variable handles. A variable corresponds to
1766 /// the XPathVariable type, and a variable handle is simply a pointer to XPathVariable.
1767 /// \n \n
1768 /// In order to get variable information, you can use one of the following functions:
1769 /// @code
1770 /// const char_t* Mezzanine::XML::XPathVariable::Name() const;
1771 /// Mezzanine::XML::XPathValueType Mezzanine::XML::XPathVariable::Type() const;
1772 /// @endcode
1773 /// Note that each variable has a distinct type which is specified upon variable creation and can not be changed later.
1774 /// \n \n
1775 /// In order to get variable value, you should use one of the following functions, depending on the variable type:
1776 /// @code
1777 /// bool Mezzanine::XML::XPathVariable::GetBoolean() const;
1778 /// double Mezzanine::XML::XPathVariable::GetNumber() const;
1779 /// const char_t* Mezzanine::XML::XPathVariable::GetString() const;
1780 /// const Mezzanine::XML::XPathNodeSet& Mezzanine::XML::XPathVariable::GetNodeSet() const;
1781 /// @endcode
1782 /// These functions return the value of the variable. Note that no type conversions are performed; if the type mismatch occurs, a dummy value is returned (false for booleans, NaN for
1783 /// numbers, empty string for strings and empty set for node sets).
1784 /// \n \n
1785 /// In order to set variable value, you should use one of the following functions, depending on the variable type:
1786 /// @code
1787 /// bool XPathVariable::Set(bool Value);
1788 /// bool XPathVariable::Set(double Value);
1789 /// bool XPathVariable::Set(const char_t* Value);
1790 /// bool XPathVariable::Set(const XPathNodeSet& Value);
1791 /// @endcode
1792 /// These functions modify the variable value. Note that no type conversions are performed; if the type mismatch occurs, the functions return false; they also return false on allocation
1793 /// failure. The variable values are copied to the internal variable storage, so you can modify or destroy them after the functions return.
1794 /// \n \n
1795 /// This is an example of using variables in XPath queries:
1796 /// @code
1797 /// // Select nodes via compiled query
1798 /// Mezzanine::XML::XPathVariableSet vars;
1799 /// vars.Add("remote", Mezzanine::XML::XPathTypeBoolean);
1800 ///
1801 /// Mezzanine::XML::XPathQuery QueryRemoteTools("/Profile/Tools/Tool[@AllowRemote = string($remote)]", &vars);
1802 ///
1803 /// vars.Set("remote", true);
1804 /// XPathNodeSet ToolsRemote = QueryRemoteTools.EvaluateNodeSet(doc);
1805 ///
1806 /// vars.Set("remote", false);
1807 /// Mezzanine::XML::XPathNodeSet ToolsLocal = QueryRemoteTools.EvaluateNodeSet(doc);
1808 ///
1809 /// std::cout << "Remote tool: ";
1810 /// ToolsRemote[2].GetNode().Print(std::cout);
1811 ///
1812 /// std::cout << "Local tool: ";
1813 /// ToolsLocal[0].GetNode().Print(std::cout);
1814 ///
1815 /// // You can pass the context directly to FindNodes/FindNode
1816 /// Mezzanine::XML::XPathNodeSet ToolsLocalImm = doc.FindNodes("/Profile/Tools/Tool[@AllowRemote = string($remote)]", &vars);
1817 ///
1818 /// std::cout << "Local tool imm: ";
1819 /// ToolsLocalImm[0].GetNode().Print(std::cout);
1820 /// @endcode
1821 /// @subsection XMLXPathError Error Handling
1822 /// There are two different mechanisms for error handling in XPath implementation; the mechanism used depends on whether exception support is disabled (this is controlled with
1823 /// XML_NO_EXCEPTIONS define).
1824 /// \n \n
1825 /// By default, XPath functions throw Mezzanine::XML::XPathException object in case of errors; additionally, in the event any memory allocation fails, an std::bad_alloc exception is thrown. Also
1826 /// Mezzanine::XML::XPathException is thrown if the query is evaluated to a node set, but the return type is not node set. If the query constructor succeeds (i.e. no exception is thrown), the query
1827 /// object is valid. Otherwise you can get the error details via one of the following functions:
1828 /// @code
1829 /// virtual const char* Mezzanine::XML::XPathException::what() const throw();
1830 /// const Mezzanine::XML::XPathParseResult& Mezzanine::XML::XPathException::Result() const;
1831 /// @endcode
1832 /// If exceptions are disabled, then in the event of parsing failure the query is initialized to invalid state; you can test if the query object is valid by using it in a boolean
1833 /// expression: if (query) { ... }. Additionally, you can get parsing result via the Result() accessor:
1834 /// @code
1835 /// const XPathParseResult& XPathQuery::Result() const;
1836 /// @endcode
1837 /// Without exceptions, evaluating invalid query results in false, empty string, NaN or an empty node set, depending on the type; evaluating a query as a node set results in an empty
1838 /// node set if the return type is not node set.
1839 /// \n \n
1840 /// The information about parsing result is returned via Mezzanine::XML::XPathParseResult object. It contains parsing status and the offset of last successfully parsed character from the
1841 /// beginning of the source stream.
1842 /// \n \n
1843 /// Parsing result is represented as the error message; it is either a null pointer, in case there is no error, or the error message in the form of ASCII zero-terminated string.
1844 /// \n \n
1845 /// The Description() member function can be used to get the error message; it never returns the null pointer, so you can safely use Description() even if query parsing succeeded.
1846 /// \n \n
1847 /// In addition to the error message, parsing result has an OffSet member, which contains the offset of last successfully parsed character. This offset is in units of Mezzanine::XML::char_t
1848 /// (bytes for character mode, wide characters for wide character mode).
1849 /// \n \n
1850 /// Parsing result object can be implicitly converted to bool like this: if (result) { ... } else { ... }.
1851 /// \n \n
1852 /// This is an example of XPath error handling:
1853 /// @code
1854 /// // Exception is thrown for incorrect query syntax
1855 /// try
1856 /// {
1857 /// doc.FindNodes("//nodes[#true()]");
1858 /// }
1859 /// catch (const Mezzanine::XML::XPathException& e)
1860 /// {
1861 /// std::cout << "Select failed: " << e.what() << std::endl;
1862 /// }
1863 ///
1864 /// // Exception is thrown for incorrect query semantics
1865 /// try
1866 /// {
1867 /// doc.FindNodes("(123)/next");
1868 /// }
1869 /// catch (const Mezzanine::XML::XPathException& e)
1870 /// {
1871 /// std::cout << "Select failed: " << e.what() << std::endl;
1872 /// }
1873 ///
1874 /// // Exception is thrown for query with incorrect return type
1875 /// try
1876 /// {
1877 /// doc.FindNodes("123");
1878 /// }
1879 /// catch (const Mezzanine::XML::XPathException& e)
1880 /// {
1881 /// std::cout << "Select failed: " << e.what() << std::endl;
1882 /// }
1883 /// @endcode
1884 /// @subsection XMLXPathStandards Conformance to W3C Specification
1885 /// Because of the differences in document object models, performance considerations and implementation complexity, pugixml does not provide a fully conformant XPath 1.0 implementation.
1886 /// This is the current list of incompatibilities:
1887 /// - Consecutive text nodes sharing the same parent are not merged, i.e. in <node>text1 <![CDATA[data]]> text2 </node> node should have one text node children, but instead has
1888 /// three.
1889 /// - Since the document type declaration is not used for parsing, id() function always returns an empty node set.
1890 /// - Namespace nodes are not supported (affects namespace:: axis).
1891 /// - Name tests are performed on QNames in XML document instead of expanded names; for <foo xmlns:ns1='uri' xmlns:ns2='uri'> <ns1:child/> <ns2:child/> </foo>, query foo/ns1:*
1892 /// will return only the first child, not both of them. Compliant XPath implementations can return both nodes if the user provides appropriate namespace declarations.
1893 /// - String functions consider a character to be either a single char value or a single wchar_t value, depending on the library configuration; this means that some string functions
1894 /// are not fully Unicode-aware. This affects substring(), string-length() and translate() functions.
1895 
1896 
1897 
1898 /**
1899 @page OriginalpugixmlLicense Original pugixml License
1900 The original pugixml software had the following license text:
1901 @section pugixmloriginallicense Original Text
1902 @verbatim
1903 The pugixml library is distributed under the MIT license:
1904 
1905  Copyright (c) 2006-2010 Arseny Kapoulkine
1906 
1907  Permission is hereby granted, free of charge, to any person obtaining a copy of this software
1908  and associated documentation files (the "Software"), to deal in the Software without restriction,
1909  including without limitation the rights to use, copy, modify, merge, publish, distribute,
1910  sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
1911  furnished to do so, subject to the following conditions:
1912 
1913  The above copyright notice and this permission notice shall be included in all copies or
1914  substantial portions of the Software.
1915 
1916  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
1917  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1918  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
1919  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1920  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1921 
1922 This means that you can freely use pugixml in your applications, both open-source and proprietary.
1923 If you use pugixml in a product, it is sufficient to add an acknowledgment like this to the product
1924 distribution:
1925 
1926  This software is based on pugixml library (http://pugixml.org).
1927  pugixml is Copyright (C) 2006-2010 Arseny Kapoulkine.
1928 @endverbatim
1929 \n \n
1930 The documentation was copied with permission per the copyright notice near the bottom of Table of contents and several other pages as follows:
1931 \n \n
1932 @verbatim
1933 Copyright © 2010 Arseny Kapoulkine
1934 Distributed under the MIT License
1935 @endverbatim
1936 */
1937 
1938 #endif
1939 
1940 /*
1941  * Copyright © 2006-2012 Arseny Kapoulkine
1942  *
1943  * Permission is hereby granted, free of charge, to any person
1944  * obtaining a copy of this software and associated documentation
1945  * files (the "Software"), to deal in the Software without
1946  * restriction, including without limitation the rights to use,
1947  * copy, modify, merge, publish, distribute, sublicense, and/or sell
1948  * copies of the Software, and to permit persons to whom the
1949  * Software is furnished to do so, subject to the following
1950  * conditions:
1951  *
1952  * The above copyright notice and this permission notice shall be
1953  * included in all copies or substantial portions of the Software.
1954  *
1955  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1956  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
1957  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1958  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
1959  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
1960  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1961  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1962  * OTHER DEALINGS IN THE SOFTWARE.
1963  */