pugixml is a light-weight C++ XML
@@ -69,7 +69,7 @@
No documentation is perfect, neither is this one. If you encounter a description
- that is unclear, please file an issue as described in Feedback.
+ that is unclear, please file an issue as described in Feedback.
Also if you can spare the time for a full proof-reading, including spelling
and grammar, that would be great! Please send me
an e-mail; as a token of appreciation, your name will be included
@@ -80,7 +80,7 @@
If you believe you've found a bug in pugixml (bugs include compilation problems
@@ -107,14 +107,14 @@
Your contribution has to be distributed under the terms of a license that's
compatible with pugixml license; i.e. GPL/LGPL licensed code is not accepted.
-
- If filing an issue is not possible due to privacy or
- other concerns, you can contact pugixml author by e-mail directly: arseny.kapoulkine@gmail.com.
+
+ If filing an issue is not possible due to privacy or other concerns, you
+ can contact pugixml author by e-mail directly: arseny.kapoulkine@gmail.com.
pugixml 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 functions that do not modify the tree except for XPath-related
- functions; see XPath for XPath reference. As discussed in C++ interface,
+ functions; see XPath for XPath reference. As discussed in C++ interface,
there are two types of handles to tree data - xml_node
and xml_attribute. The handles have special
null (empty) values which propagate through various functions and thus are
@@ -58,12 +58,11 @@
- 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 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), and 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 functions roughly correspond
@@ -124,6 +123,7 @@
all attributes like this (samples/traverse_base.cpp):
- 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.
- node_document nodes do not have a name
- or value, node_element and node_declaration
- nodes always have a name but never have a value, node_pcdata,
+
+ 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. node_document
+ nodes do not have a name or value, node_element
+ and node_declaration nodes always
+ have a name but never have a value, node_pcdata,
node_cdata, node_comment
and node_doctype nodes never have a name
but always have a value (it may be empty though), node_pi
@@ -164,9 +164,8 @@
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.
-
- It is common to store data as text contents
- of some node - i.e. <node><description>Thisisanode</description></node>.
+
+ It is common to store data as text contents of some node - i.e. <node><description>Thisisanode</description></node>.
In this case, <description> node does not have a value, but instead
has a child of type node_pcdata with value
"This is a node". pugixml
@@ -189,7 +188,7 @@
text()
returns a special object that can be used for working with PCDATA contents
in more complex cases than just retrieving the value; it is described in
- Working with text contents sections.
+ Working with text contents sections.
- All
- attributes have name and value, both of which are strings (value may be empty).
- There are two corresponding accessors, like for xml_node:
+
+ All attributes have name and value, both of which are strings (value may
+ be empty). There are two corresponding accessors, like for xml_node:
constchar_t*xml_attribute::name()const;constchar_t*xml_attribute::value()const;
@@ -212,12 +210,12 @@
In case the attribute handle is null, both functions return empty strings
- they never return null pointers.
-
- If you need a non-empty string if
- the attribute handle is null (for example, you need to get the option value
- from XML attribute, but if it is not specified, you need it to default to
- "sorted" instead of
- ""), you can use as_string accessor:
+
+ If you need a non-empty string if the attribute handle is null (for example,
+ you need to get the option value from XML attribute, but if it is not specified,
+ you need it to default to "sorted"
+ instead of ""), you
+ can use as_string accessor:
@@ -226,12 +224,11 @@
the attribute handle is null. If you do not specify the argument, the function
is equivalent to value().
-
- 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 represented as strings
- in XML. pugixml provides several accessors that convert attribute value to
- some other type:
+
+ 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 represented as strings in XML. pugixml provides several
+ accessors that convert attribute value to some other type:
intxml_attribute::as_int(intdef=0)const;unsignedintxml_attribute::as_uint(unsignedintdef=0)const;
@@ -296,11 +293,12 @@
long type, including string conversions.
-
- This is an example of using these functions,
- along with node data retrieval ones (samples/traverse_base.cpp):
+
+ This is an example of using these functions, along with node data retrieval
+ ones (samples/traverse_base.cpp):
- 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 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:
+
+ 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 having a unique id: <group><itemid="1"/><itemid="2"/></group>. There are two functions for finding
+ child nodes based on the attribute values:
xml_nodexml_node::find_child_by_attribute(constchar_t*name,constchar_t*attr_name,constchar_t*attr_value)const;xml_nodexml_node::find_child_by_attribute(constchar_t*attr_name,constchar_t*attr_value)const;
@@ -370,6 +363,7 @@
This is an example of using these functions (samples/traverse_base.cpp):
+
std::cout<<"Tool for *.dae generation: "<<tools.find_child_by_attribute("Tool","OutputFileMasks","*.dae").attribute("Filename").value()<<"\n";
@@ -383,13 +377,12 @@
- If your
- C++ compiler supports range-based for-loop (this is a C++11 feature, at the
- time of writing it's supported by Microsoft Visual Studio 11 Beta, GCC 4.6
- and Clang 3.0), you can use it to enumerate nodes/attributes. Additional
+
+ If your C++ compiler supports range-based for-loop (this is a C++11 feature,
+ at the time of writing it's supported by Microsoft Visual Studio 11 Beta,
+ GCC 4.6 and Clang 3.0), you can use it to enumerate nodes/attributes. Additional
helpers are provided to support this; note that they are also compatible
with Boost Foreach,
and possibly other pre-C++11 foreach facilities.
@@ -410,6 +403,7 @@
This is an example of using these functions (samples/traverse_rangefor.cpp):
- Child node lists and attribute lists are simply
- double-linked lists; while you can use previous_sibling/next_sibling and other such functions for
+
+ Child node lists and attribute lists are simply double-linked lists; while
+ you can use previous_sibling/next_sibling and other such functions for
iteration, pugixml additionally provides node and attribute iterators, so
that you can treat nodes as containers of other nodes or attributes:
@@ -486,6 +480,7 @@
Here is an example of using iterators for document traversal (samples/traverse_iter.cpp):
- 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 equivalent method.
- However, pugixml provides a helper for depth-first traversal of a subtree.
- In order to use it, you have to implement xml_tree_walker
+
+ 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 equivalent method. However, pugixml provides a
+ helper for depth-first traversal of a subtree. In order to use it, you have
+ to implement xml_tree_walker
interface and to call traverse
function:
- The traversal
- is launched by calling traverse
+
+ The traversal is launched by calling traverse
function on traversal root and proceeds as follows:
@@ -570,10 +564,10 @@
begin or end
functions; their default implementations return true.
-
- You can get the node's depth relative
- to the traversal root at any point by calling depth
- function. It returns -1
+
+ You can get the node's depth relative to the traversal root at any point
+ by calling depth function.
+ It returns -1
if called from begin/end, and returns 0-based depth if called
from for_each - depth is
0 for all children of the traversal root, 1 for all grandchildren and so
@@ -583,22 +577,24 @@
This is an example of traversing tree hierarchy with xml_tree_walker (samples/traverse_walker.cpp):
- 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 through nodes/attributes
- until the needed one is found, you can make a predicate and call one of
- find_ functions:
+
+ 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 through nodes/attributes until the needed one is found,
+ you can make a predicate and call one of find_
+ functions:
template<typenamePredicate>xml_attributexml_node::find_attribute(Predicatepred)const;template<typenamePredicate>xml_nodexml_node::find_child(Predicatepred)const;
@@ -658,6 +654,7 @@
This is an example of using predicate-based functions (samples/traverse_predicate.cpp):
// Find child via predicate (looks for direct children only)
-std::cout<<tools.find_child(allow_remote_predicate()).attribute("Filename").value()<<std::endl;
+
// Find child via predicate (looks for direct children only)
+std::cout<<tools.find_child(allow_remote_predicate()).attribute("Filename").value()<<std::endl;
-// Find node via predicate (looks for all descendants in depth-first order)
-std::cout<<doc.find_node(allow_remote_predicate()).attribute("Filename").value()<<std::endl;
+// Find node via predicate (looks for all descendants in depth-first order)
+std::cout<<doc.find_node(allow_remote_predicate()).attribute("Filename").value()<<std::endl;
-// Find attribute via predicate
-std::cout<<tools.last_child().find_attribute(allow_remote_predicate()).value()<<std::endl;
+// Find attribute via predicate
+std::cout<<tools.last_child().find_attribute(allow_remote_predicate()).value()<<std::endl;
-// We can use simple functions instead of function objects
-std::cout<<tools.find_child(small_timeout).attribute("Filename").value()<<std::endl;
+// We can use simple functions instead of function objects
+std::cout<<tools.find_child(small_timeout).attribute("Filename").value()<<std::endl;
- It is common to store data as text contents of some
- node - i.e. <node><description>Thisisanode</description></node>.
+
+ It is common to store data as text contents of some node - i.e. <node><description>Thisisanode</description></node>.
In this case, <description> node does not have a value, but instead
has a child of type node_pcdata with value
"This is a node". pugixml
@@ -711,10 +708,8 @@
in the documentation for modifying document
data; this section describes the access interface of xml_text.
-
- You can get the text object from a node by using
- text()
- method:
+
+ You can get the text object from a node by using text() method:
xml_textxml_node::text()const;
@@ -724,11 +719,11 @@
itself is used to return data; otherwise, a first child node of type node_pcdata or node_cdata
is used.
-
- You
- can check if the text object is bound to a valid PCDATA/CDATA node by using
- it as a boolean value, i.e. if(text)
- {...} or if
+
+ You can check if the text object is bound to a valid PCDATA/CDATA node by
+ using it as a boolean value, i.e. if
+ (text){...
+ } or if(!text){...}. Alternatively you can check it
by using the empty()
@@ -736,9 +731,9 @@
boolxml_text::empty()const;
-
- Given a text object, you can get the contents
- (i.e. the value of PCDATA/CDATA node) by using the following function:
+
+ Given a text object, you can get the contents (i.e. the value of PCDATA/CDATA
+ node) by using the following function:
constchar_t*xml_text::get()const;
@@ -746,11 +741,10 @@
In case text object is empty, the function returns an empty string - it never
returns a null pointer.
-
- If
- you need a non-empty string if the text object is empty, or if the text contents
- is actually a number or a boolean that is stored as a string, you can use
- the following accessors:
+
+ If you need a non-empty string if the text object is empty, or if the text
+ contents is actually a number or a boolean that is stored as a string, you
+ can use the following accessors:
constchar_t*xml_text::as_string(constchar_t*def="")const;intxml_text::as_int(intdef=0)const;
@@ -767,9 +761,9 @@
to a target type using the same rules and restrictions. You can refer
to documentation for the attribute functions for details.
-
- xml_text
- is essentially a helper class that operates on xml_node
+
+ xml_text is essentially a
+ helper class that operates on xml_node
values. It is bound to a node of type node_pcdata
or node_cdata. You can use the following
function to retrieve this node:
@@ -787,6 +781,7 @@
object (samples/text.cpp):
- If you need to get the document root of some
- node, you can use the following function:
+
+ If you need to get the document root of some node, you can use the following
+ function:
xml_nodexml_node::root()const;
@@ -811,11 +806,10 @@
which is the root node of the document the node belongs to (unless the node
is null, in which case null node is returned).
-
- While
- pugixml supports complex XPath expressions, sometimes a simple path handling
- facility is needed. There are two functions, for getting node path and for
- converting path to a node:
+
+ While pugixml supports complex XPath expressions, sometimes a simple path
+ handling facility is needed. There are two functions, for getting node path
+ and for converting path to a node:
string_txml_node::path(char_tdelimiter='/')const;xml_nodexml_node::first_element_by_path(constchar_t*path,char_tdelimiter='/')const;
@@ -860,13 +854,12 @@
is defined.
-
- pugixml 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 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 beginning
- of XML buffer:
+
+ pugixml 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 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 beginning of XML buffer:
+ Major release, featuring a lot of performance improvements and some new features.
+
+
+
+ Specification changes:
+
+
+ xml_document::load(const char_t*) was renamed to load_string; the
+ old method is still available and will be deprecated in a future
+ release
+
+
+ xml_node::select_single_node was renamed to select_node; the old
+ method is still available and will be deprecated in a future release.
+
+
+
+
+ New features:
+
+
+ Added xml_node::append_move and other functions for moving nodes
+ within a document
+
+
+ Added xpath_query::evaluate_node for evaluating queries with a single
+ node as a result
+
+
+
+
+ Performance improvements:
+
+
+ Optimized XML parsing (10-40% faster with clang/gcc, up to 10% faster
+ with MSVC)
+
+
+ Optimized memory consumption when copying nodes in the same document
+ (string contents is now shared)
+
+
+ Optimized node copying (10% faster for cross-document copies, 3x
+ faster for inter-document copies; also it now consumes a constant
+ amount of stack space)
+
+
+ Optimized node output (60% faster; also it now consumes a constant
+ amount of stack space)
+
+
+ Optimized XPath allocation (query evaluation now results in fewer
+ temporary allocations)
+
+
+ Optimized XPath sorting (node set sorting is 2-3x faster in some
+ cases)
+
+
+ Optimized XPath evaluation (XPathMark suite is 100x faster; some
+ commonly used queries are 3-4x faster)
+
+
+
+
+ Compatibility improvements:
+
+
+ Fixed xml_node::offset_debug for corner cases
+
+
+ Fixed undefined behavior while calling memcpy in some cases
+
+
+ Fixed MSVC 2015 compilation warnings
+
+
+ Fixed contrib/foreach.hpp for Boost 1.56.0
+
+
+
+
+ Bug fixes
+
+
+ Adjusted comment output to avoid malformed documents if the comment
+ value contains "--"
+
+
+ Fix XPath sorting for documents that were constructed using append_buffer
+
The XML document is represented with a tree data structure. The root of the
@@ -66,9 +66,9 @@
which correspond to C++ type xml_attribute,
and some additional data (i.e. name).
-
- The tree nodes can be of one of the following
- types (which together form the enumeration xml_node_type):
+
+ The tree nodes can be of one of the following types (which together form
+ the enumeration xml_node_type):
@@ -81,6 +81,7 @@
several ways, which are covered below. There can be only one document
node in the tree; document node does not have any XML representation.
+
Element/tag node (node_element) - this
@@ -188,7 +189,7 @@
(its parent should be the document). The example XML representation of
a document type declaration node is as follows:
-
<!DOCTYPEgreeting[<!ELEMENTgreeting(#PCDATA)>]>
+
<!DOCTYPEgreeting[<!ELEMENTgreeting(#PCDATA)>]>
Here the node has value "greeting [ <!ELEMENT
@@ -208,6 +209,7 @@
@@ -259,18 +261,21 @@
some operations on xml_node
are only valid for certain node types. The classes are described below.
-
- xml_document is the owner of the entire
- document structure; it is a non-copyable class. The interface of xml_document consists of loading functions
- (see Loading document), saving functions (see Saving document) and the entire
- interface of xml_node, which
- allows for document inspection and/or modification. Note that while xml_document is a sub-class of xml_node, xml_node
- is not a polymorphic type; the inheritance is present only to simplify usage.
- Alternatively you can use the document_element
- function to get the element node that's the immediate child of the document.
+
+ xml_document is the owner
+ of the entire document structure; it is a non-copyable class. The interface
+ of xml_document consists
+ of loading functions (see Loading document), saving functions (see Saving document)
+ and the entire interface of xml_node,
+ which allows for document inspection and/or modification. Note that while
+ xml_document is a sub-class
+ of xml_node, xml_node is not a polymorphic type; the
+ inheritance is present only to simplify usage. Alternatively you can use
+ the document_element function
+ to get the element node that's the immediate child of the document.
-
- Default constructor of xml_document
+
+ Default constructor of xml_document
initializes the document to the tree with only a root node (document node).
You can then populate it with data using either tree modification functions
or loading functions; all loading functions destroy the previous tree with
@@ -295,12 +300,12 @@
are destroyed.
-
- xml_node
- is the handle to document node; it can point to any node in the document,
- including the document node itself. There is a common interface for nodes
- of all types; the actual node type can
- be queried via the xml_node::type() method. Note that xml_node
+
+ xml_node is the handle to
+ document node; it can point to any node in the document, including the document
+ node itself. There is a common interface for nodes of all types; the actual
+ node type can be queried via the xml_node::type()
+ method. Note that xml_node
is only a handle to the actual node, not the node itself - you can have several
xml_node handles pointing
to the same underlying object. Destroying xml_node
@@ -310,8 +315,8 @@
a pointer; you can safely pass or return xml_node
objects by value without additional overhead.
-
- There is a special value of xml_node
+
+ There is a special value of xml_node
type, known as null node or empty node (such nodes have type node_null). It does not correspond to any
node in any document, and thus resembles null pointer. However, all operations
are defined on empty nodes; generally the operations don't do anything and
@@ -321,40 +326,37 @@
have a parent, the first parent() call returns null node; the second parent()
call then also returns null node, which makes error handling easier.
-
- xml_attribute
- is the handle to an XML attribute; it has the same semantics as xml_node, i.e. there can be several xml_attribute handles pointing to the same
- underlying object and there is a special null attribute value, which propagates
- to function results.
+
+ xml_attribute is the handle
+ to an XML attribute; it has the same semantics as xml_node,
+ i.e. there can be several xml_attribute
+ handles pointing to the same underlying object and there is a special null
+ attribute value, which propagates to function results.
-
- Both xml_node and xml_attribute
- have the default constructor which initializes them to null objects.
+
+ Both xml_node and xml_attribute have the default constructor
+ which initializes them to null objects.
-
- xml_node and 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 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 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
- relational comparison operators except for search optimization (i.e. associative
- container keys).
+
+ xml_node and 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 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 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 relational comparison
+ operators except for search optimization (i.e. associative container keys).
-
- If
- you want to use xml_node
+
+ If you want to use xml_node
or xml_attribute objects
as keys in hash-based associative containers, you can use the hash_value member functions. They return
the hash values that are guaranteed to be the same for all handles to the
same underlying object. The hash value for null handles is 0.
-
- 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){...
+
+ 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(!node){...}else{...}.
@@ -377,14 +379,14 @@
There are two choices of interface and internal representation when configuring
pugixml: you can either choose the UTF-8 (also called char) interface or
UTF-16/32 (also called wchar_t) one. The choice is controlled via PUGIXML_WCHAR_MODE
define; you can set it via pugiconfig.hpp or via preprocessor options, as
- discussed in Additional configuration
+ discussed in Additional configuration
options. If this define is set, the wchar_t
interface is used; otherwise (by default) the char interface is used. The
exact wide character encoding is assumed to be either UTF-16 or UTF-32 and
@@ -416,13 +418,13 @@
- There is a special type, pugi::char_t, that is defined as the character
- type and depends on the library configuration; it will be also used in the
- documentation hereafter. There is also a type pugi::string_t,
- which is defined as the STL string of the character type; it corresponds
- to std::string in char mode and to std::wstring
- in wchar_t mode.
+
+ There is a special type, pugi::char_t,
+ that is defined as the character type and depends on the library configuration;
+ it will be also used in the documentation hereafter. There is also a type
+ pugi::string_t, which is defined as the STL string
+ of the character type; it corresponds to std::string
+ in char mode and to std::wstring in wchar_t mode.
In addition to the interface, the internal implementation changes to store
@@ -434,10 +436,9 @@
inconvenient to process and most of your XML data is non-ASCII, wchar_t mode
is probably a better choice.
-
- There are cases when you'll have
- to convert string data between UTF-8 and wchar_t encodings; the following
- helper functions are provided for such purposes:
+
+ There are cases when you'll have to convert string data between UTF-8 and
+ wchar_t encodings; the following helper functions are provided for such purposes:
- 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 functions with set_memory_management function. The
- function interfaces are the same as that of malloc/free:
+
+ 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 functions with set_memory_management function.
+ The function interfaces are the same as that of malloc/free:
- You can use the following accessor
- functions to change or get current memory management functions:
+
+ You can use the following accessor functions to change or get current memory
+ management functions:
voidset_memory_management_functions(allocation_functionallocate,deallocation_functiondeallocate);allocation_functionget_memory_allocation_function();
@@ -589,6 +589,7 @@
This is a simple example of custom memory management (samples/custom_memory_management.cpp):
@@ -640,6 +642,7 @@
is 32 Kb; for some applications the size is too large (i.e. embedded
systems with little heap space or applications that keep lots of XML
documents in memory). A minimum size of 1 Kb is recommended.
+
PUGIXML_MEMORY_OUTPUT_STACK
@@ -649,6 +652,7 @@
using node output from threads with little stack space, decreasing
this value can prevent stack overflows. A minimum size of 1 Kb is recommended.
When the document is loaded from file/buffer, unless an inplace loading
- function is used (see Loading document from memory), a complete copy of character
+ function is used (see Loading document from memory), a complete copy of character
stream is made; all 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 (i.e. if the xml_document object is destroyed or if another
@@ -711,7 +715,7 @@
pugixml is distributed in source form. You can either download a source distribution
- or checkout the Subversion repository.
+ or clone the Git repository.
The distribution contains library source, documentation (the manual you're
@@ -80,56 +80,54 @@
line endings. Otherwise the files in both archives are identical.
- The Subversion repository is located at http://pugixml.googlecode.com/svn/.
- There is a Subversion tag "release-{version}" for each version;
- also there is the "latest" tag, which always points to the latest
- stable release.
+ The Git repository is located at https://github.com/zeux/pugixml/.
+ There is a Git tag "v{version}" for each version; also there
+ is the "latest" tag, which always points to the latest stable
+ release.
For example, to checkout the current version, you can use this command:
The repository contains library source, documentation, code examples and
full unit test suite.
- Use latest version tag if you want to automatically get new versions via
- svn update. Use other tags if you want to switch to
- new versions only explicitly (for example, using svn switch
- command). Also please note that Subversion trunk contains the work-in-progress
- version of the code; while this means that you can get new features and
- bug fixes from trunk without waiting for a new release, this also means
- that occasionally the code can be broken in some configurations.
+ Use latest version tag if you want to automatically get new versions. Use
+ other tags if you want to switch to new versions only explicitly. Also
+ please note that the master branch contains the work-in-progress version
+ of the code; while this means that you can get new features and bug fixes
+ from master without waiting for a new release, this also means that occasionally
+ the code can be broken in some configurations.
- The Subversion repository is mirrored by a Git repository at https://github.com/zeux/pugixml.
- The mirror is frequently updated and has the same structure in terms of
- tags and contents as Subversion repository.
+ You can access the Git repository via Subversion using https://github.com/zeux/pugixml
+ URL. For example, to checkout the current version, you can use this command:
pugixml is distributed in source form without any pre-built binaries; you
@@ -139,7 +137,7 @@
The complete pugixml source consists of three files - one source file, pugixml.cpp,
and two header files, pugixml.hpp and pugiconfig.hpp. pugixml.hpp is the primary
header which you need to include in order to use pugixml classes/functions;
- pugiconfig.hpp is a supplementary configuration file (see Additional configuration
+ pugiconfig.hpp is a supplementary configuration file (see Additional configuration
options).
The rest of this guide assumes that pugixml.hpp is either in the current directory
or in one of include directories of your projects, so that #include"pugixml.hpp"
@@ -149,7 +147,7 @@
@@ -194,7 +192,7 @@
are project files for Apple XCode3, Code::Blocks, Codelite, Microsoft Visual
Studio 2005, 2008, 2010, and configuration scripts for CMake and premake4.
You're welcome to submit project files/build scripts for other software;
- see Feedback.
+ see Feedback.
There are two projects for each version of Microsoft Visual Studio: one
@@ -247,7 +245,7 @@
@@ -358,7 +356,7 @@
as character type) and UTF-16/32 style interface (the in-memory text encoding
is assumed to be UTF-16/32, depending on wchar_t
size, most functions use wchar_t
- as character type). See Unicode interface for more details.
+ as character type). See Unicode interface for more details.
@@ -406,7 +404,7 @@
PUGIXML_MEMORY_PAGE_SIZE, PUGIXML_MEMORY_OUTPUT_STACK
and PUGIXML_MEMORY_XPATH_PAGE_SIZE
can be used to customize certain important sizes to optimize memory usage
- for the application-specific patterns. For details see Memory consumption tuning.
+ for the application-specific patterns. For details see Memory consumption tuning.
pugixml provides several functions for loading XML data from various places
@@ -49,26 +49,25 @@
EOL handling or attribute value normalization) can impact 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
- control whether certain XML nodes are parsed; see Parsing options for
+ control whether certain XML nodes are parsed; see Parsing options for
more information.
- XML data is always converted to internal character format (see Unicode interface)
+ XML data is always converted to internal character format (see Unicode interface)
before parsing. pugixml 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 of UTF-16) and handles all encoding conversions
automatically. Unless explicit 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 document encoding. Encoding
- conversion is described in more detail in Encodings.
+ conversion is described in more detail in Encodings.
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 Encodings). The path has the target
+ optional arguments, which specify parsing options (see Parsing options)
+ and input data encoding (see Encodings). 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 should have the exact case if
the target file system is case-sensitive, etc.
@@ -95,12 +94,13 @@
The result of the operation is returned in an xml_parse_result
object; this object contains the operation status and the related information
(i.e. last successfully parsed position in the input file, if parsing fails).
- See Handling parsing errors for error handling details.
+ See Handling parsing errors for error handling details.
- 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 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 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 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:
+
+ 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 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 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 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:
xml_parse_resultxml_document::load_buffer(constvoid*contents,size_tsize,unsignedintoptions=parse_default,xml_encodingencoding=encoding_auto);xml_parse_resultxml_document::load_buffer_inplace(void*contents,size_tsize,unsignedintoptions=parse_default,xml_encodingencoding=encoding_auto);
@@ -135,7 +135,7 @@
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
- options (see Parsing options) and input data encoding (see Encodings).
+ options (see Parsing options) and input data encoding (see Encodings).
The buffer does not have to be zero-terminated.
@@ -163,12 +163,11 @@
is the recommended function if you have to load the document from memory
and performance is critical.
-
- There is also a simple helper function
- for cases when you want to load the XML document from null-terminated character
- string:
+
+ There is also a simple helper function for cases when you want to load the
+ XML document from null-terminated character string:
// You can use load_buffer to load document from immutable memory block:
-pugi::xml_parse_resultresult=doc.load_buffer(source,size);
+
// You can use load_buffer to load document from immutable memory block:
+pugi::xml_parse_resultresult=doc.load_buffer(source,size);
+
-
// You can use load_buffer_inplace to load document from mutable memory block; the block's lifetime must exceed that of document
-char*buffer=newchar[size];
+
// You can use load_buffer_inplace to load document from mutable memory block; the block's lifetime must exceed that of document
+char*buffer=newchar[size];memcpy(buffer,source,size);
-// The block can be allocated by any method; the block is modified during parsing
-pugi::xml_parse_resultresult=doc.load_buffer_inplace(buffer,size);
+// The block can be allocated by any method; the block is modified during parsing
+pugi::xml_parse_resultresult=doc.load_buffer_inplace(buffer,size);
-// You have to destroy the block yourself after the document is no longer used
-delete[]buffer;
+// You have to destroy the block yourself after the document is no longer used
+delete[]buffer;
+
-
// You can use load_buffer_inplace_own to load document from mutable memory block and to pass the ownership of this block
-// The block has to be allocated via pugixml allocation function - using i.e. operator new here is incorrect
-char*buffer=static_cast<char*>(pugi::get_memory_allocation_function()(size));
+
// You can use load_buffer_inplace_own to load document from mutable memory block and to pass the ownership of this block
+// The block has to be allocated via pugixml allocation function - using i.e. operator new here is incorrect
+char*buffer=static_cast<char*>(pugi::get_memory_allocation_function()(size));memcpy(buffer,source,size);
-// The block will be deleted by the document
-pugi::xml_parse_resultresult=doc.load_buffer_inplace_own(buffer,size);
+// The block will be deleted by the document
+pugi::xml_parse_resultresult=doc.load_buffer_inplace_own(buffer,size);
+
-
// You can use load to load document from null-terminated strings, for example literals:
-pugi::xml_parse_resultresult=doc.load("<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>");
+
// You can use load to load document from null-terminated strings, for example literals:
+pugi::xml_parse_resultresult=doc.load_string("<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>");
- To enhance interoperability, pugixml
- provides functions for loading document from any object which implements
- C++ std::istream interface. This allows you to load
- documents 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 streams, another handles wide character ones:
+
+ To enhance interoperability, pugixml provides functions for loading document
+ from any object which implements C++ std::istream
+ interface. This allows you to load documents 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 streams,
+ another handles wide character ones:
xml_parse_resultxml_document::load(std::istream&stream,unsignedintoptions=parse_default,xml_encodingencoding=encoding_auto);xml_parse_resultxml_document::load(std::wistream&stream,unsignedintoptions=parse_default);
@@ -271,6 +275,7 @@
the sample code for more complex examples involving wide streams and locales:
- All document loading functions return the
- parsing result via xml_parse_result
- object. It contains parsing status, the offset of last successfully parsed
- character from the beginning of the source stream, and the encoding of the
- source stream:
+
+ All document loading functions return the parsing result via xml_parse_result object. It contains parsing
+ status, the offset of last successfully parsed character from the beginning
+ of the source stream, and the encoding of the source stream:
- Parsing
- status is represented as the xml_parse_status
+
+ Parsing status is represented as the xml_parse_status
enumeration and can be one of the following:
@@ -309,6 +311,7 @@
status_ok means that no error was encountered
during parsing; the source stream represents the valid XML document which
was fully parsed and converted to a tree.
+
status_file_not_found is only
@@ -327,6 +330,7 @@
status_internal_error means that
something went horribly wrong; currently this error does not occur
+
status_unrecognized_tag means
@@ -373,12 +377,14 @@
indicates an empty or invalid document
-
- 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 function if you need a localized string. However
- please note that the exact messages returned by description() function may change from version to version,
- so any complex status handling should be based on status
+
+ 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 function if
+ you need a localized string. However please note that the exact messages
+ returned by description()
+ function may change from version to version, so any complex status handling
+ should be based on status
value. Note that description() returns a char
string even in PUGIXML_WCHAR_MODE;
you'll have to call as_wide to get the wchar_t string.
@@ -393,18 +399,16 @@
attribute attr will contain
the string value>somedata</node>.
-
- In addition to the status code, parsing
- result has an offset member,
- which contains the offset of last successfully parsed character if parsing
- failed because of an error in source data; otherwise offset
- is 0. For parsing efficiency reasons, pugixml does not track the current
- line during parsing; this offset is in units of pugi::char_t
- (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. Alternatively, if you're loading the document from
- memory, you can display the error chunk along with the error description
- (see the example code below).
+
+ In addition to the status code, parsing result has an offset
+ member, which contains the offset of last successfully parsed character if
+ parsing failed because of an error in source data; otherwise offset is 0. For parsing efficiency reasons,
+ pugixml does not track the current line during parsing; this offset is in
+ units of pugi::char_t (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.
+ Alternatively, if you're loading the document from memory, you can display
+ the error chunk along with the error description (see the example code below).
@@ -417,17 +421,16 @@
track the error position.
-
- Parsing result also has an encoding member, which can be used to check
- that the source data encoding was correctly guessed. It is equal to the exact
- encoding used during parsing (i.e. with the exact endianness); see Encodings for
- more information.
+
+ Parsing result also has an encoding
+ member, which can be used to check that the source data encoding was correctly
+ guessed. It is equal to the exact encoding used during parsing (i.e. with
+ the exact endianness); see Encodings for more information.
-
- Parsing result 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 as if it was a bool:
+
+ Parsing result 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 as if it was a bool:
if(doc.load_file("file.xml")){...}else{...}.
All document loading functions accept the optional parameter options. This is a bitmask that customizes
@@ -485,12 +489,14 @@
document declaration (node with type node_declaration)
is to be put in DOM tree. If this flag is off, it is not put in the tree,
but is still parsed and checked for correctness. This flag is off by default.
+
parse_doctype determines if XML document
type declaration (node with type node_doctype)
is to be put in DOM tree. If this flag is off, it is not put in the tree,
but is still parsed and checked for correctness. This flag is off by default.
+
parse_pi determines if processing instructions
@@ -498,18 +504,21 @@
in DOM tree. If this flag is off, they are 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.
+
parse_comments determines if comments
(nodes with type node_comment) are
to be put in DOM tree. If this flag is off, they are not put in the tree,
but are still parsed and checked for correctness. This flag is off by default.
+
parse_cdata determines if CDATA sections
(nodes with type node_cdata) are to
be put in DOM tree. If this flag is off, they are not put in the tree,
but are still parsed and checked for correctness. This flag is on by default.
+
parse_trim_pcdata determines if leading
@@ -518,6 +527,7 @@
often the application only cares about the non-whitespace contents so
it's easier to trim whitespace from text during parsing. This flag is
off by default.
+
parse_ws_pcdata determines if PCDATA
@@ -536,6 +546,7 @@
one child when parse_ws_pcdata
is not set. This flag is off by default.
+
parse_ws_pcdata_single determines
@@ -554,6 +565,7 @@
This flag has no effect if parse_ws_pcdata
is enabled. This flag is off by default.
+
parse_fragment determines if document
@@ -598,6 +610,7 @@
ones). If character/entity reference can not be expanded, it is 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.
+
parse_eol determines if EOL handling (that
@@ -607,6 +620,7 @@
be performed on input data (that is, comments contents, PCDATA/CDATA
contents and attribute values). This flag is on
by default.
+
parse_wconv_attribute determines
@@ -617,6 +631,7 @@
is set, i.e. \r\n
is converted to a single space. This flag is on
by default.
+
parse_wnorm_attribute determines
@@ -656,6 +671,7 @@
so theoretically it is the fastest mode. However, as mentioned above,
in practice parse_default is usually
equally fast.
+
parse_default is the default set of flags,
@@ -665,6 +681,7 @@
in attribute values and performing EOL handling. Note, that PCDATA sections
consisting only of whitespace characters are not parsed (by default)
for performance reasons.
+
parse_full is the set of flags which adds
@@ -681,23 +698,24 @@
This is an example of using different parsing options (samples/load_options.cpp):
+
constchar*source="<!--comment--><node><</node>";
-// Parsing with default options; note that comment node is not added to the tree, and entity reference < is expanded
-doc.load(source);
+// Parsing with default options; note that comment node is not added to the tree, and entity reference < is expanded
+doc.load_string(source);std::cout<<"First node value: ["<<doc.first_child().value()<<"], node child value: ["<<doc.child_value("node")<<"]\n";
-// Parsing with additional parse_comments option; comment node is now added to the tree
-doc.load(source,pugi::parse_default|pugi::parse_comments);
+// Parsing with additional parse_comments option; comment node is now added to the tree
+doc.load_string(source,pugi::parse_default|pugi::parse_comments);std::cout<<"First node value: ["<<doc.first_child().value()<<"], node child value: ["<<doc.child_value("node")<<"]\n";
-// Parsing with additional parse_comments option and without the (default) parse_escapes option; < is not expanded
-doc.load(source,(pugi::parse_default|pugi::parse_comments)&~pugi::parse_escapes);
+// Parsing with additional parse_comments option and without the (default) parse_escapes option; < is not expanded
+doc.load_string(source,(pugi::parse_default|pugi::parse_comments)&~pugi::parse_escapes);std::cout<<"First node value: ["<<doc.first_child().value()<<"], node child value: ["<<doc.child_value("node")<<"]\n";
-// Parsing with minimal option mask; comment node is not added to the tree, and < is not expanded
-doc.load(source,pugi::parse_minimal);
+// Parsing with minimal option mask; comment node is not added to the tree, and < is not expanded
+doc.load_string(source,pugi::parse_minimal);std::cout<<"First node value: ["<<doc.first_child().value()<<"], node child value: ["<<doc.child_value("node")<<"]\n";
- pugixml 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 of UTF-16) and handles
- all encoding conversions. Most loading functions accept the optional parameter
- encoding. This is a value
- of enumeration type xml_encoding,
+
+ pugixml 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 of UTF-16) and handles all encoding conversions. Most
+ loading functions accept the optional parameter encoding.
+ This is a value of enumeration type xml_encoding,
that can have the following values:
- As discussed
- before, nodes can have name and value, both of which are strings. Depending
- on node type, name or value may be absent. node_document
+
+ As discussed before, nodes can have name and value, both of which are strings.
+ Depending on node type, name or value may be absent. node_document
nodes do not have a name or value, node_element
and node_declaration nodes always
have a name but never have a value, node_pcdata,
@@ -98,31 +98,31 @@
This is an example of setting node name and value (samples/modify_base.cpp):
+
pugi::xml_nodenode=doc.child("node");
-// change node name
-std::cout<<node.set_name("notnode");
+// change node name
+std::cout<<node.set_name("notnode");std::cout<<", new node name: "<<node.name()<<std::endl;
-// change comment text
-std::cout<<doc.last_child().set_value("useless comment");
+// change comment text
+std::cout<<doc.last_child().set_value("useless comment");std::cout<<", new comment text: "<<doc.last_child().value()<<std::endl;
-// we can't change value of the element or name of the comment
-std::cout<<node.set_value("1")<<", "<<doc.last_child().set_name("2")<<std::endl;
+// we can't change value of the element or name of the comment
+std::cout<<node.set_value("1")<<", "<<doc.last_child().set_name("2")<<std::endl;
- All
- attributes have name and value, both of which are strings (value may be empty).
- You can set them with the following functions:
+
+ All attributes have name and value, both of which are strings (value may
+ be empty). You can set them with the following functions:
boolxml_attribute::set_name(constchar_t*rhs);boolxml_attribute::set_value(constchar_t*rhs);
@@ -177,8 +177,8 @@
including string conversions.
-
- For convenience, all set_value
+
+ For convenience, all set_value
functions have the corresponding assignment operators:
xml_attribute&xml_attribute::operator=(constchar_t*rhs);
@@ -199,19 +199,20 @@
This is an example of setting attribute name and value (samples/modify_base.cpp):
+
pugi::xml_attributeattr=node.attribute("id");
-// change attribute name/value
-std::cout<<attr.set_name("key")<<", "<<attr.set_value("345");
+// change attribute name/value
+std::cout<<attr.set_name("key")<<", "<<attr.set_value("345");std::cout<<", new attribute: "<<attr.name()<<"="<<attr.value()<<std::endl;
-// we can use numbers or booleans
-attr.set_value(1.234);
+// we can use numbers or booleans
+attr.set_value(1.234);std::cout<<"new attribute value: "<<attr.value()<<std::endl;
-// we can also use assignment operators for more concise code
-attr=true;
+// we can also use assignment operators for more concise code
+attr=true;std::cout<<"final attribute value: "<<attr.value()<<std::endl;
- Nodes
- and attributes do not exist without a document tree, so you can't create
+
+ 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 node/attribute list or before/after some other node:
@@ -317,19 +317,20 @@
This is an example of adding new attributes/nodes to the document (samples/modify_add.cpp):
+
-
// add node with some name
-pugi::xml_nodenode=doc.append_child("node");
+
// add node with some name
+pugi::xml_nodenode=doc.append_child("node");
-// add description node with text child
-pugi::xml_nodedescr=node.append_child("description");
+// add description node with text child
+pugi::xml_nodedescr=node.append_child("description");descr.append_child(pugi::node_pcdata).set_value("Simple node");
-// add param node before the description
-pugi::xml_nodeparam=node.insert_child_before("param",descr);
+// add param node before the description
+pugi::xml_nodeparam=node.insert_child_before("param",descr);
-// add attributes to param node
-param.append_attribute("name")="version";
+// add attributes to param node
+param.append_attribute("name")="version";param.append_attribute("value")=1.1;param.insert_attribute_after("type",param.attribute("name"))="float";
- If
- you do not want your document to contain some node or attribute, you can
+
+ If you do not want your document to contain some node or attribute, you can
remove it with one of the following functions:
boolxml_node::remove_attribute(constxml_attribute&a);
@@ -394,17 +394,18 @@
This is an example of removing attributes/nodes from the document (samples/modify_remove.cpp):
+
-
// remove description node with the whole subtree
-pugi::xml_nodenode=doc.child("node");
+
// remove description node with the whole subtree
+pugi::xml_nodenode=doc.child("node");node.remove_child("description");
-// remove id attribute
-pugi::xml_nodeparam=node.child("param");
+// remove id attribute
+pugi::xml_nodeparam=node.child("param");param.remove_attribute("value");
-// we can also remove nodes/attributes by handles
-pugi::xml_attributeid=param.attribute("name");
+// we can also remove nodes/attributes by handles
+pugi::xml_attributeid=param.attribute("name");param.remove_attribute(id);
pugixml provides a special class, xml_text,
@@ -421,8 +422,8 @@
documentation for accessing document data; this section describes
the modification interface of xml_text.
-
- Once you have an xml_text
+
+ Once you have an xml_text
object, you can set the text contents using the following function:
boolxml_text::set(constchar_t*rhs);
@@ -439,9 +440,9 @@
an element node, this function creates the PCDATA child node if necessary
(i.e. if the element node does not have a PCDATA/CDATA child already).
-
- In addition to a string function, several
- functions are provided for handling text with numbers and booleans as contents:
+
+ In addition to a string function, several functions are provided for handling
+ text with numbers and booleans as contents:
+ For convenience, all set
functions have the corresponding assignment operators:
xml_text&xml_text::operator=(constchar_t*rhs);
@@ -480,29 +481,30 @@
object to modify text contents (samples/text.cpp):
+
-
// change project version
-project.child("version").text()=1.2;
+
// change project version
+project.child("version").text()=1.2;
-// add description element and set the contents
-// note that we do not have to explicitly add the node_pcdata child
-project.append_child("description").text().set("a test project");
+// add description element and set the contents
+// note that we do not have to explicitly add the node_pcdata child
+project.append_child("description").text().set("a test project");
- 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 needed operation, pugixml 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 - you have to immediately insert
- it somewhere in the tree. For this, you can use one of the following functions:
+
+ 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 needed operation, pugixml 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 - you have to
+ immediately insert it somewhere in the tree. For this, you can use one of
+ the following functions:
xml_attributexml_node::append_copy(constxml_attribute&proto);xml_attributexml_node::prepend_copy(constxml_attribute&proto);
@@ -559,6 +561,7 @@
node cloning and usage of other document modification functions:
+
boolload_preprocess(pugi::xml_document&doc,constchar*path);
@@ -570,23 +573,23 @@
{pugi::xml_nodeinclude=child;
- // load new preprocessed document (note: ideally this should handle relative paths)
- constchar*path=include.value();
+ // load new preprocessed document (note: ideally this should handle relative paths)
+constchar*path=include.value();pugi::xml_documentdoc;if(!load_preprocess(doc,path))returnfalse;
- // insert the comment marker above include directive
- node.insert_child_before(pugi::node_comment,include).set_value(path);
+ // insert the comment marker above include directive
+node.insert_child_before(pugi::node_comment,include).set_value(path);
- // copy the document above the include directive (this retains the original order!)
- for(pugi::xml_nodeic=doc.first_child();ic;ic=ic.next_sibling())
+ // copy the document above the include directive (this retains the original order!)
+for(pugi::xml_nodeic=doc.first_child();ic;ic=ic.next_sibling()){node.insert_copy_before(ic,include);}
- // remove the include node and move to the next child
- child=child.next_sibling();
+ // remove the include node and move to the next child
+child=child.next_sibling();node.remove_child(include);}
@@ -603,8 +606,8 @@
boolload_preprocess(pugi::xml_document&doc,constchar*path){
- pugi::xml_parse_resultresult=doc.load_file(path,pugi::parse_default|pugi::parse_pi);// for <?include?>
-
+ pugi::xml_parse_resultresult=doc.load_file(path,pugi::parse_default|pugi::parse_pi);// for <?include?>
+returnresult?preprocess(doc):false;}
+ Sometimes instead of cloning a node you need to move an existing node to
+ a different position in a tree. This can be accomplished by copying the node
+ and removing the original; however, this is expensive since it results in
+ a lot of extra operations. For moving nodes within the same document tree,
+ you can use of the following functions instead:
+
- pugixml provides several ways to assemble
- an XML document from other XML documents. Assuming there is a set of document
- fragments, represented as in-memory buffers, the implementation choices are
- as follows:
+ These functions mirror the structure of append_copy,
+ prepend_copy, insert_copy_before and insert_copy_after
+ - they take the handle to the moved object and move it to the appropriate
+ place with all attributes and/or child nodes. The functions return the handle
+ to the resulting object (which is the same as the moved object), or null
+ handle on failure.
+
+
+ The failure conditions resemble those of append_child,
+ insert_child_before and related
+ functions, consult their documentation
+ for more information. There are additional caveats specific to moving
+ functions:
+
+
+
+ Moving null handles results in operation failure;
+
+
+ Moving is only possible for nodes that belong to the same document; attempting
+ to move nodes between documents will fail.
+
+
+ insert_move_after and
+ insert_move_before functions
+ fail if the moved node is the same as the node
+ argument (this operation would be a no-op otherwise).
+
+
+ It is impossible to move a subtree to a child of some node inside this
+ subtree, i.e. node.append_move(node.parent().parent());
+ will fail.
+
+ pugixml provides several ways to assemble an XML document from other XML
+ documents. Assuming there is a set of document fragments, represented as
+ in-memory buffers, the implementation choices are as follows:
Use a temporary document to parse the data from a string, then clone
@@ -668,10 +722,10 @@
- the input buffer is a byte buffer, with size in bytes; the buffer is not
modified and can be freed after the function returns.
-
- Since append_buffer
- needs to append child nodes to the current node, it only works if the current
- node is either document or element node. Calling append_buffer
+
+ Since append_buffer needs
+ to append child nodes to the current node, it only works if the current node
+ is either document or element node. Calling append_buffer
on a node with any other type results in an error with status_append_invalid_root
status.
Often after creating a new document or loading the existing one and processing
@@ -46,8 +46,8 @@
include debug printing, serialization via network or other text-oriented medium,
etc. pugixml provides several functions to output any subtree of the document
to a file, stream or another generic transport interface; these functions allow
- to customize the output format (see Output options), and also perform
- necessary encoding conversions (see Encodings). This section documents
+ to customize the output format (see Output options), and also perform
+ necessary encoding conversions (see Encodings). This section documents
the relevant functionality.
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 encoding (see Encodings). The path has the target
+ arguments, which specify indentation and other output options (see Output options)
+ and output data encoding (see Encodings). 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 should have the exact case if
the target file system is case-sensitive, etc.
@@ -93,39 +92,38 @@
a special file opening function if it is provided by the runtime library
or converts the path to UTF-8 and uses the system file opening function.
-
- save_file
- 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 document contents. If the file could not be opened, the function
- returns false. Calling save_file is equivalent to creating an
- xml_writer_file object with
- FILE*
+
+ save_file 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 document
+ contents. If the file could not be opened, the function returns false. Calling save_file
+ is equivalent to creating an xml_writer_file
+ object with FILE*
handle as the only constructor argument and then calling save;
- see Saving document via writer interface for writer interface details.
+ see Saving document via writer interface for writer interface details.
- To enhance interoperability pugixml
- provides functions for saving document to any object which implements C++
- std::ostream interface. This allows you to save
- documents to any 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 std::cout
+
+ To enhance interoperability pugixml provides functions for saving document
+ to any object which implements C++ std::ostream
+ interface. This allows you to save documents to any 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 std::cout
stream as saving target. There are two functions, one works with narrow character
streams, another handles wide character ones:
@@ -145,19 +143,20 @@
you 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.
-
- Calling save
- with stream target is equivalent to creating an xml_writer_stream
- object with stream as the only constructor argument and then calling save; see Saving document via writer interface for writer
+
+ Calling save with stream
+ target is equivalent to creating an xml_writer_stream
+ object with stream as the only constructor argument and then calling save; see Saving document via writer interface for writer
interface details.
This is a simple example of saving XML document to standard output (samples/save_stream.cpp):
+
-
// save document to standard output
-std::cout<<"Document:\n";
+
// save document to standard output
+std::cout<<"Document:\n";doc.save(std::cout);
- All
- of the above saving functions are implemented in terms of writer interface.
+
+ All of the above saving functions are implemented in terms of writer interface.
This is a simple interface with a single function, which is called several
times during output process with chunks of document data as input:
@@ -205,6 +203,7 @@
read the sample code for more complex examples:
- While
- the previously described functions save the whole document to the destination,
+
+ 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:
voidxml_node::print(std::ostream&os,constchar_t*indent="\t",unsignedintflags=format_default,xml_encodingencoding=encoding_auto,unsignedintdepth=0)const;
@@ -248,21 +246,22 @@
illustrates the difference:
+
-
// get a test document
-pugi::xml_documentdoc;
-doc.load("<foo bar='baz'><call>hey</call></foo>");
+
// get a test document
+pugi::xml_documentdoc;
+doc.load_string("<foo bar='baz'><call>hey</call></foo>");
-// print document to standard output (prints <?xml version="1.0"?><foo bar="baz"><call>hey</call></foo>)
-doc.save(std::cout,"",pugi::format_raw);
+// print document to standard output (prints <?xml version="1.0"?><foo bar="baz"><call>hey</call></foo>)
+doc.save(std::cout,"",pugi::format_raw);std::cout<<std::endl;
-// print document to standard output as a regular node (prints <foo bar="baz"><call>hey</call></foo>)
-doc.print(std::cout,"",pugi::format_raw);
+// print document to standard output as a regular node (prints <foo bar="baz"><call>hey</call></foo>)
+doc.print(std::cout,"",pugi::format_raw);std::cout<<std::endl;
-// print a subtree to standard output (prints <call>hey</call>)
-doc.child("foo").child("call").print(std::cout,"",pugi::format_raw);
+// print a subtree to standard output (prints <call>hey</call>)
+doc.child("foo").child("call").print(std::cout,"",pugi::format_raw);std::cout<<std::endl;
All saving functions accept the optional parameter flags.
@@ -302,6 +301,7 @@
node's depth relative to the output subtree. This flag has no effect
if format_raw is enabled. This flag
is on by default.
+
format_raw switches between formatted and
@@ -312,6 +312,7 @@
with parse_ws_pcdata flag, to
preserve the original document formatting as much as possible. This flag
is off by default.
+
format_no_escapes disables output
@@ -337,6 +338,7 @@
the document contents. Enabling this flag disables this declaration.
This flag has no effect in xml_node::print
functions: they never output the default declaration. This flag is off by default.
+
format_write_bom enables Byte Order
@@ -372,43 +374,44 @@
This is an example that shows the outputs of different output options (samples/save_options.cpp):
+
-
// get a test document
-pugi::xml_documentdoc;
-doc.load("<foo bar='baz'><call>hey</call></foo>");
+
// get a test document
+pugi::xml_documentdoc;
+doc.load_string("<foo bar='baz'><call>hey</call></foo>");
-// default options; prints
-// <?xml version="1.0"?>
-// <foo bar="baz">
-// <call>hey</call>
-// </foo>
-doc.save(std::cout);
+// default options; prints
+// <?xml version="1.0"?>
+// <foo bar="baz">
+// <call>hey</call>
+// </foo>
+doc.save(std::cout);std::cout<<std::endl;
-// default options with custom indentation string; prints
-// <?xml version="1.0"?>
-// <foo bar="baz">
-// --<call>hey</call>
-// </foo>
-doc.save(std::cout,"--");
+// default options with custom indentation string; prints
+// <?xml version="1.0"?>
+// <foo bar="baz">
+// --<call>hey</call>
+// </foo>
+doc.save(std::cout,"--");std::cout<<std::endl;
-// default options without indentation; prints
-// <?xml version="1.0"?>
-// <foo bar="baz">
-// <call>hey</call>
-// </foo>
-doc.save(std::cout,"\t",pugi::format_default&~pugi::format_indent);// can also pass "" instead of indentation string for the same effect
-std::cout<<std::endl;
+// default options without indentation; prints
+// <?xml version="1.0"?>
+// <foo bar="baz">
+// <call>hey</call>
+// </foo>
+doc.save(std::cout,"\t",pugi::format_default&~pugi::format_indent);// can also pass "" instead of indentation string for the same effect
+std::cout<<std::endl;
-// raw output; prints
-// <?xml version="1.0"?><foo bar="baz"><call>hey</call></foo>
-doc.save(std::cout,"\t",pugi::format_raw);
+// raw output; prints
+// <?xml version="1.0"?><foo bar="baz"><call>hey</call></foo>
+doc.save(std::cout,"\t",pugi::format_raw);std::cout<<std::endl<<std::endl;
-// raw output without declaration; prints
-// <foo bar="baz"><call>hey</call></foo>
-doc.save(std::cout,"\t",pugi::format_raw|pugi::format_no_declaration);
+// raw output without declaration; prints
+// <foo bar="baz"><call>hey</call></foo>
+doc.save(std::cout,"\t",pugi::format_raw|pugi::format_no_declaration);std::cout<<std::endl;
pugixml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little
@@ -424,7 +427,7 @@
it's a strict subset 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 possible values for the encoding are documented in Encodings;
+ The possible values for the encoding are documented in Encodings;
the only flag that has a different meaning is encoding_auto.
When you are saving the document using xml_document::save() or xml_document::save_file(), a default XML document declaration is
@@ -490,22 +493,23 @@
This is an example that shows how to create a custom declaration node (samples/save_declaration.cpp):
+
-
// get a test document
-pugi::xml_documentdoc;
-doc.load("<foo bar='baz'><call>hey</call></foo>");
+
// get a test document
+pugi::xml_documentdoc;
+doc.load_string("<foo bar='baz'><call>hey</call></foo>");
-// add a custom declaration node
-pugi::xml_nodedecl=doc.prepend_child(pugi::node_declaration);
+// add a custom declaration node
+pugi::xml_nodedecl=doc.prepend_child(pugi::node_declaration);decl.append_attribute("version")="1.0";decl.append_attribute("encoding")="UTF-8";decl.append_attribute("standalone")="no";
-// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
-// <foo bar="baz">
-// <call>hey</call>
-// </foo>
-doc.save(std::cout);
+// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
+// <foo bar="baz">
+// <call>hey</call>
+// </foo>
+doc.save(std::cout);std::cout<<std::endl;
If the task at hand is to select a subset of document nodes that match some
@@ -48,7 +48,7 @@
for these cases. pugixml implements an almost 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 can be found
- in Conformance to W3C specification. The rest of this section describes the interface for XPath
+ in Conformance to W3C specification. The rest of this section describes the interface for XPath
functionality. Please note that if you wish to learn to use XPath language,
you have to look for other tutorials or manuals; for example, you can read
W3Schools XPath tutorial,
@@ -58,12 +58,11 @@
- Because an XPath node can be either a node or an
- attribute, there is a special type, xpath_node,
- which is a discriminated union of these types. A value of this type contains
- two node handles, one of xml_node
+
+ Because an XPath node can be either a node or an attribute, there is a special
+ type, xpath_node, which is
+ a discriminated union of these types. A value of this type contains two node
+ handles, one of xml_node
type, and another one of xml_attribute
type; at most one of them can be non-null. The accessors to get these handles
are available:
@@ -102,33 +101,30 @@
handle. For null nodes, parent
returns null handle.
-
- 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
+
+ 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 each other.
-
- 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 attribute and node arguments
- (in which case the attribute must belong to the attribute list of the node).
- The constructor from xml_node
- is implicit, so you can usually pass xml_node
- to functions that expect xpath_node.
- Apart from that you usually don't need to create your own XPath node objects,
- since they are returned to you via selection functions.
+
+ 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 attribute and node arguments (in which case the attribute must
+ belong to the attribute list of the node). The constructor from xml_node is implicit, so you can usually
+ pass xml_node to functions
+ that expect xpath_node. Apart
+ from that you usually don't need to create your own XPath node objects, since
+ they are returned to you via selection functions.
-
- 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 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 corresponding document.
+
+ 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 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 corresponding document.
-
- Node sets are represented by xpath_node_set
+
+ Node sets are represented by xpath_node_set
object, which has an interface that resembles one of sequential random-access
containers. It has an iterator type along with usual begin/past-the-end iterator
accessors:
@@ -137,9 +133,8 @@
const_iteratorxpath_node_set::begin()const;const_iteratorxpath_node_set::end()const;
-
- And it also can be iterated via indices, just
- like std::vector:
+
+ And it also can be iterated via indices, just like std::vector:
constxpath_node&xpath_node_set::operator[](size_tindex)const;size_txpath_node_set::size()const;
@@ -152,9 +147,9 @@
set size results in undefined behavior. You can use both iterator-based and
index-based access for iteration, however the iterator-based one can be faster.
-
- The order of iteration depends on the order of
- nodes inside the set; the order can be queried via the following function:
+
+ The order of iteration depends on the order of nodes inside the set; the
+ order can be queried via the following function:
enumxpath_node_set::type_t{type_unsorted,type_sorted,type_sorted_reverse};type_txpath_node_set::type()const;
@@ -178,10 +173,9 @@
will return type_sorted or
type_sorted_reverse.
-
- Often the actual iteration is not needed;
- instead, only the first element in document order is required. For this,
- a special accessor is provided:
+
+ Often the actual iteration is not needed; instead, only the first element
+ in document order is required. For this, a special accessor is provided:
xpath_nodexpath_node_set::first()const;
@@ -193,11 +187,10 @@
the complexity does - if the set is sorted, the complexity is constant, otherwise
it is linear in the number of elements or worse.
-
- 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 which takes
- an iterator range (const_iterator
+
+ 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 which takes an iterator range (const_iterator
is a typedef for constxpath_node*), and an optional type:
select_nodes function compiles
the expression and then executes it with the node as a context node, and
- returns the resulting node set. select_single_node
+ returns the resulting node set. select_node
returns only the first node in document order from the result, and is equivalent
to calling select_nodes(query).first().
If the XPath expression does not match anything, or the node handle is null,
select_nodes returns an empty
- set, and select_single_node
- returns null XPath node.
+ set, and select_node returns
+ null XPath node.
If exception handling is not disabled, both functions throw xpath_exception
if the query can not be compiled or if it returns a value with type other
- than node set; see Error handling for details.
+ than node set; see Error handling for details.
-
- 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 similar queries, consider compiling them into query objects
- (see Using query objects for further reference). Once you get a compiled query
- object, you can pass it to select functions instead of an expression string:
+
+ 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 similar queries, consider compiling them into query
+ objects (see Using query objects for further reference). Once you get a compiled
+ query object, you can pass it to select functions instead of an expression
+ string:
+ When you call select_nodes
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 can be needed in the following circumstances:
@@ -307,30 +300,29 @@
operator and store pointers to xpath_query
in the container.
-
- You can create a query object with the constructor
- that takes XPath expression as an argument:
+
+ You can create a query object with the constructor that takes XPath expression
+ as an argument:
- The expression is compiled and the
- compiled representation is stored in the new query object. If compilation
- fails, xpath_exception is thrown if
- exception handling is not disabled (see Error handling for details).
- After the query is created, you can query the type of the evaluation result
- using the following function:
+
+ The expression is compiled and the compiled representation is stored in the
+ new query object. If compilation fails, xpath_exception
+ is thrown if exception handling is not disabled (see Error handling for
+ details). After the query is created, you can query the type of the evaluation
+ result using the following function:
xpath_value_typexpath_query::return_type()const;
-
- You
- can evaluate the query using one of the following functions:
+
+ You can evaluate the query using one of the following functions:
All functions take the context node as an argument, compute the expression
@@ -339,8 +331,9 @@
value, but no type other than node set can be converted to node set. Because
of this, evaluate_boolean,
evaluate_number and evaluate_string always return a result,
- but evaluate_node_set results
- in an error if the return type is not node set (see Error handling).
+ but evaluate_node_set and
+ evaluate_node result in an
+ error if the return type is not node set (see Error handling).
@@ -349,12 +342,12 @@
Calling node.select_nodes("query")
- is equivalent to calling xpath_query("query").evaluate_node_set(node).
+ is equivalent to calling xpath_query("query").evaluate_node_set(node). Calling node.select_node("query") is equivalent to calling xpath_query("query").evaluate_node(node).
-
- Note that evaluate_string function returns the STL
- string; as such, it's not available in PUGIXML_NO_STL
+
+ Note that evaluate_string
+ function returns the STL string; as such, it's not available in PUGIXML_NO_STL
mode and also usually allocates memory. There is another string evaluation
function:
XPath queries may contain references to variables; this is useful if you
@@ -426,10 +420,10 @@
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 is passed to xpath_query
- constructor or to select_nodes/select_single_node functions:
+ constructor or to select_nodes/select_node functions:
@@ -470,9 +463,8 @@
0 for numbers, false for booleans, empty string for strings
and empty set for node sets.
-
- You can get the existing variables
- with the following functions:
+
+ You can get the existing variables with the following functions:
xpath_variable*xpath_variable_set::get(constchar_t*name);constxpath_variable*xpath_variable_set::get(constchar_t*name)const;
@@ -481,14 +473,13 @@
The functions return the variable handle, or null pointer if the variable
with the specified name is not found.
-
- 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 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 not perform any type conversions.
+
+ 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 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 not perform any type conversions.
boolxpath_variable_set::set(constchar_t*name,boolvalue);boolxpath_variable_set::set(constchar_t*name,doublevalue);
@@ -499,15 +490,14 @@
The variable values are copied to the internal variable storage, so you can
modify or destroy them after the functions return.
-
- 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 the xpath_variable type, and a variable handle
- is simply a pointer to xpath_variable.
+
+ 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 the xpath_variable
+ type, and a variable handle is simply a pointer to xpath_variable.
-
- In
- order to get variable information, you can use one of the following functions:
+
+ In order to get variable information, you can use one of the following functions:
constchar_t*xpath_variable::name()const;xpath_value_typexpath_variable::type()const;
@@ -516,9 +506,8 @@
Note that each variable has a distinct type which is specified upon variable
creation and can not be changed later.
-
- In
- order to get variable value, you should use one of the following functions,
+
+ In order to get variable value, you should use one of the following functions,
depending on the variable type:
boolxpath_variable::get_boolean()const;
@@ -531,9 +520,9 @@
are performed; if the type mismatch occurs, a dummy value is returned (false for booleans, NaN
for numbers, empty string for strings and empty set for node sets).
-
- In order to set variable value, you should
- use one of the following functions, depending on the variable type:
+
+ In order to set variable value, you should use one of the following functions,
+ depending on the variable type:
boolxpath_variable::set(boolvalue);boolxpath_variable::set(doublevalue);
@@ -550,9 +539,10 @@
This is an example of using variables in XPath queries (samples/xpath_variables.cpp):
+
-
// Select nodes via compiled query
-pugi::xpath_variable_setvars;
+
// Select nodes via compiled query
+pugi::xpath_variable_setvars;vars.add("remote",pugi::xpath_type_boolean);pugi::xpath_queryquery_remote_tools("/Profile/Tools/Tool[@AllowRemote = string($remote)]",&vars);
@@ -569,8 +559,8 @@
std::cout<<"Local tool: ";tools_local[0].node().print(std::cout);
-// You can pass the context directly to select_nodes/select_single_node
-pugi::xpath_node_settools_local_imm=doc.select_nodes("/Profile/Tools/Tool[@AllowRemote = string($remote)]",&vars);
+// You can pass the context directly to select_nodes/select_node
+pugi::xpath_node_settools_local_imm=doc.select_nodes("/Profile/Tools/Tool[@AllowRemote = string($remote)]",&vars);std::cout<<"Local tool imm: ";tools_local_imm[0].node().print(std::cout);
@@ -580,7 +570,7 @@
There are two different mechanisms for error handling in XPath implementation;
@@ -588,23 +578,21 @@
is controlled with PUGIXML_NO_EXCEPTIONS
define).
-
- By default, XPath functions throw xpath_exception object in case of errors;
- additionally, in the event any memory allocation fails, an std::bad_alloc
- exception is thrown. Also xpath_exception
- 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 object is valid. Otherwise you can get the error details via one
- of the following functions:
+
+ By default, XPath functions throw xpath_exception
+ object in case of errors; additionally, in the event any memory allocation
+ fails, an std::bad_alloc exception is thrown. Also xpath_exception 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 object is valid.
+ Otherwise you can get the error details via one of the following functions:
- 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 expression: if
+
+ 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 expression: if(query){...}. Additionally, you can get parsing
result via the result() accessor:
@@ -617,9 +605,8 @@
a query as a node set results in an empty node set if the return type is
not node set.
-
- The information about parsing result is
- returned via xpath_parse_result
+
+ The information about parsing result is returned via xpath_parse_result
object. It contains parsing status and the offset of last successfully parsed
character from the beginning of the source stream:
- 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.
+
+ 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.
-
- 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. Note that description() returns a char
- string even in PUGIXML_WCHAR_MODE;
- you'll have to call as_wide to get the wchar_t string.
+ 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. Note that
+ description()
+ returns a char string even in
+ PUGIXML_WCHAR_MODE; you'll
+ have to call as_wide to get the wchar_t string.
-
- In addition to the error message,
- parsing result has an offset
+
+ 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 pugi::char_t (bytes
for character mode, wide characters for wide character mode).
-
- Parsing result object can be implicitly
- converted to bool like this:
- if(result){...}
+
+ Parsing result object can be implicitly converted to bool
+ like this: if(result){...}else{...}.
// Exception is thrown for incorrect query syntax
-try
+
// Exception is thrown for incorrect query syntax
+try{doc.select_nodes("//nodes[#true()]");}
@@ -673,8 +660,8 @@
std::cout<<"Select failed: "<<e.what()<<std::endl;}
-// Exception is thrown for incorrect query semantics
-try
+// Exception is thrown for incorrect query semantics
+try{doc.select_nodes("(123)/next");}
@@ -683,8 +670,8 @@
std::cout<<"Select failed: "<<e.what()<<std::endl;}
-// Exception is thrown for query with incorrect return type
-try
+// Exception is thrown for query with incorrect return type
+try{doc.select_nodes("123");}
@@ -698,7 +685,7 @@
pugixml is a light-weight C++ XML
@@ -59,7 +59,7 @@
No documentation is perfect, neither is this one. If you encounter a description
- that is unclear, please file an issue as described in Feedback. Also if
+ that is unclear, please file an issue as described in Feedback. Also if
you can spare the time for a full proof-reading, including spelling and
grammar, that would be great! Please send me an e-mail;
as a token of appreciation, your name will be included into the corresponding
@@ -69,14 +69,14 @@
pugixml provides several functions for loading XML data from various places
@@ -250,6 +250,7 @@
This is an example of loading XML document from file (samples/load_file.cpp):
+
pugi::xml_documentdoc;
@@ -281,9 +282,10 @@
This is an example of handling loading errors (samples/load_error_handling.cpp):
+
pugi::xml_documentdoc;
-pugi::xml_parse_resultresult=doc.load(source);
+pugi::xml_parse_resultresult=doc.load_string(source);if(result)std::cout<<"XML ["<<source<<"] parsed without errors, attr value: ["<<doc.child("node").attribute("attr").value()<<"]\n\n";
@@ -322,6 +324,7 @@
read the sample code for more examples:
// You can use load_buffer_inplace to load document from mutable memory block; the block's lifetime must exceed that of document
-char*buffer=newchar[size];
+
// You can use load_buffer_inplace to load document from mutable memory block; the block's lifetime must exceed that of document
+char*buffer=newchar[size];memcpy(buffer,source,size);
-// The block can be allocated by any method; the block is modified during parsing
-pugi::xml_parse_resultresult=doc.load_buffer_inplace(buffer,size);
+// The block can be allocated by any method; the block is modified during parsing
+pugi::xml_parse_resultresult=doc.load_buffer_inplace(buffer,size);
-// You have to destroy the block yourself after the document is no longer used
-delete[]buffer;
+// You have to destroy the block yourself after the document is no longer used
+delete[]buffer;
@@ -348,6 +352,7 @@
the sample code for more complex examples involving wide streams and locales:
pugixml features an extensive interface for getting various types of data
@@ -394,6 +399,7 @@
This is an example of using these functions (samples/traverse_base.cpp):
std::cout<<"Tool for *.dae generation: "<<tools.find_child_by_attribute("Tool","OutputFileMasks","*.dae").attribute("Filename").value()<<"\n";
@@ -438,6 +445,7 @@
Here is an example of using iterators for document traversal (samples/traverse_iter.cpp):
for(pugi::xml_nodetool:tools.children("Tool")){
@@ -499,22 +508,24 @@
This is an example of traversing tree hierarchy with xml_tree_walker (samples/traverse_walker.cpp):
The document in pugixml is fully mutable: you can completely change the document
@@ -590,36 +602,38 @@
example of setting node/attribute name and value (samples/modify_base.cpp):
+
pugi::xml_nodenode=doc.child("node");
-// change node name
-std::cout<<node.set_name("notnode");
+// change node name
+std::cout<<node.set_name("notnode");std::cout<<", new node name: "<<node.name()<<std::endl;
-// change comment text
-std::cout<<doc.last_child().set_value("useless comment");
+// change comment text
+std::cout<<doc.last_child().set_value("useless comment");std::cout<<", new comment text: "<<doc.last_child().value()<<std::endl;
-// we can't change value of the element or name of the comment
-std::cout<<node.set_value("1")<<", "<<doc.last_child().set_name("2")<<std::endl;
+// we can't change value of the element or name of the comment
+std::cout<<node.set_value("1")<<", "<<doc.last_child().set_name("2")<<std::endl;
+
pugi::xml_attributeattr=node.attribute("id");
-// change attribute name/value
-std::cout<<attr.set_name("key")<<", "<<attr.set_value("345");
+// change attribute name/value
+std::cout<<attr.set_name("key")<<", "<<attr.set_value("345");std::cout<<", new attribute: "<<attr.name()<<"="<<attr.value()<<std::endl;
-// we can use numbers or booleans
-attr.set_value(1.234);
+// we can use numbers or booleans
+attr.set_value(1.234);std::cout<<"new attribute value: "<<attr.value()<<std::endl;
-// we can also use assignment operators for more concise code
-attr=true;
+// we can also use assignment operators for more concise code
+attr=true;std::cout<<"final attribute value: "<<attr.value()<<std::endl;
@@ -649,19 +663,20 @@
This is an example of adding new attributes/nodes to the document (samples/modify_add.cpp):
+
-
// add node with some name
-pugi::xml_nodenode=doc.append_child("node");
+
// add node with some name
+pugi::xml_nodenode=doc.append_child("node");
-// add description node with text child
-pugi::xml_nodedescr=node.append_child("description");
+// add description node with text child
+pugi::xml_nodedescr=node.append_child("description");descr.append_child(pugi::node_pcdata).set_value("Simple node");
-// add param node before the description
-pugi::xml_nodeparam=node.insert_child_before("param",descr);
+// add param node before the description
+pugi::xml_nodeparam=node.insert_child_before("param",descr);
-// add attributes to param node
-param.append_attribute("name")="version";
+// add attributes to param node
+param.append_attribute("name")="version";param.append_attribute("value")=1.1;param.insert_attribute_after("type",param.attribute("name"))="float";
@@ -681,17 +696,18 @@
This is an example of removing attributes/nodes from the document (samples/modify_remove.cpp):
+
-
// remove description node with the whole subtree
-pugi::xml_nodenode=doc.child("node");
+
// remove description node with the whole subtree
+pugi::xml_nodenode=doc.child("node");node.remove_child("description");
-// remove id attribute
-pugi::xml_nodeparam=node.child("param");
+// remove id attribute
+pugi::xml_nodeparam=node.child("param");param.remove_attribute("value");
-// we can also remove nodes/attributes by handles
-pugi::xml_attributeid=param.attribute("name");
+// we can also remove nodes/attributes by handles
+pugi::xml_attributeid=param.attribute("name");param.remove_attribute(id);
Often after creating a new document or loading the existing one and processing
@@ -724,9 +740,10 @@
of saving XML document to file (samples/save_file.cpp):
+
-
// save document to file
-std::cout<<"Saving result: "<<doc.save_file("save_file_output.xml")<<std::endl;
+
// save document to file
+std::cout<<"Saving result: "<<doc.save_file("save_file_output.xml")<<std::endl;
@@ -743,9 +760,10 @@
This is a simple example of saving XML document to standard output (samples/save_stream.cpp):
+
-
// save document to standard output
-std::cout<<"Document:\n";
+
// save document to standard output
+std::cout<<"Document:\n";doc.save(std::cout);
@@ -765,6 +783,7 @@
read the sample code for more complex examples:
If you believe you've found a bug in pugixml, please file an issue via issue submission form.
@@ -798,14 +817,14 @@
that uses pugixml and exhibits the bug, etc. Feature requests and contributions
can be filed as issues, too.
-
- If filing an issue is not possible due to privacy or
- other concerns, you can contact pugixml author by e-mail directly: arseny.kapoulkine@gmail.com.
+
+ If filing an issue is not possible due to privacy or other concerns, you
+ can contact pugixml author by e-mail directly: arseny.kapoulkine@gmail.com.