Needful Software

pugixml

    pugixml
    Basics

    Introduction

    pugixml (http://pugixml.org/) is a light-weight C++ XML processing library.

    In this tutorial we will show how to use it to manipulate XML documents.

    Setup

    Document Creation

    The full example is available from our Codeplex repository at pugixml/DocumentCreation1.

    File: pugixml/DocumentCreation1/Source/Main.cpp

    #include <pugixml.hpp>
    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        pugi::xml_document document;
        pugi::xml_node node = document.append_child("root");
        if (node)
        {
            document.save(std::cout);
        }
        else
        {
            std::cout << "Error adding root node" << std::endl;
        }
        
    
        return 0;
    }
    

    Output

    <?xml version="1.0"?>
    <root />

    Document Loading

    The full example is available from our Codeplex repository at pugixml/DocumentLoading1.

    File: pugixml/DocumentLoading1/Source/Main.cpp

    #include <pugixml.hpp>
    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        pugi::xml_document document;
        pugi::xml_parse_result result = document.load_file("../../Source/document.xml");
        if (result)
        {
            document.save(std::cout);
        }
        else
        {
            std::cout << "Error loading document: " << result.description() << std::endl;
        }
        
        return 0;
    }
    
    PUGI__FN xml_parse_result::operator bool() const { return status == status_ok; }

    Iteration

    The full example is available from our Codeplex repository at pugixml/ChildrenIteration1.

    #include <pugixml.hpp>
    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        pugi::xml_document document;
        pugi::xml_parse_result result = document.load_file("../../Source/document.xml");
        if (result)
        {
            // Get the XML document's root element and display its name
            pugi::xml_node root = document.first_child();
            std::cout << root.name() << std::endl << std::endl;
    
            // Iterate over the children of the root node and
            // display their name and value
            for (pugi::xml_node_iterator it = root.begin();
                it != root.end();
                ++it)
            {
                std::cout << it->name() << ": " << it->child_value() << std::endl;
            }
        }
        else
        {
            std::cout << "Error loading document: " << result.description() << std::endl;
        }
        
        return 0;
    }
    

    References

      blog comments powered by Disqus