Makers Blog

pugixml a light-weight XML processing library with XPATH support

Peer PLCnext Team 09 December 2020 min. read
833 views 0 comments

Abstract

In this article I will explain how to use pugixml to process XML data. With this processing library you can use a DOM parser to read and manipulate nodes and the XPATH notation to query nodes.

How to build

To build the sources, you have to download a release from https://github.com/zeux/pugixml/tags. Now you can crosscompile the source with the PLCnext toolchain given by Phoenix Contact. The following code-snippet will show the cmake script to crosscompile.


    #Please set the environment variables to your needs 

    cmake \
    -G "Unix Malkefiles" \
    -D CMAKE_BUILD_TYPE=Release \
    -D BUILD_TESTING=OFF \
    -D BUILD_SHARED_LIBS=ON \
    -D "CMAKE_STAGING_PREFIX=${CMAKE_STAGING_PREFIX}" \
    -D "CMAKE_INSTALL_PREFIX=${CMAKE_STAGING_PREFIX}" \
-D "CMAKE_TOOLCHAIN_FILE=${ARP_TOOLCHAIN_FILE}" \
-D "ARP_TOOLCHAIN_ROOT= ${ARP_TOOLCHAIN_ROOT}" \ -D BUILD_TESTS=OFF \ -S "${SOURCE_DIRECTORY}" \ -B "${BUILD_DIRECTORY}" cmake --build "${BUILD_DIRECTORY}" --target install

How to use

First you have to integrate the C++ header and the library in your project environment. When you’re done you can use the pugixml processing.

Loading a document


    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load_file("data.xml");

    ...

Traversing subnodes from a given node

You can traverse via DOM tree and you can also manipulate the nodes.


    pugi::xpath_node_set tools = doc.select_nodes("/Profile/Tools/Tool");

    //traversing subnodes
    for (pugi::xml_node tool: tools)
    {
        std::cout << " " << tool.name();

        //getting attributes
        for (pugi::xml_attribute attr: tool.attributes())
        {
            std::cout << " " << attr.name() << "=" << attr.value();
        }
    }

Using XPATH

XPATH gives you the freedom to access nodes and attributes very easy.


    //accessing node
    pugi::xpath_node_set tools = doc.select_nodes("/Profile/Tools/Tool");
    pugi::xpath_node_set all_tools = doc.select_nodes("//Tool");

    //accessing attibutes
    auto docIdNode = doc.select_node("@ID");
    auto docIdNode_One = doc.select_node("//Tool[@ID==1]");

Saving XML document

You can save the XML document.


   doc.save_file("new_data.xml");

More Information

If you are interested in getting more information about pugixml you can check the folowing links:

License

The library is published under MIT License

Note:

The Makers Blog shows applications and user stories of community members that are not tested or reviewed by Phoenix Contact. Use them at your own risk.

Discussion

Please login/register to comment

Login/Register

Leave a Reply

Newsletter
Never miss a new article
Sign up for the newsletter
Never miss news about PLCnext Technology
Get interesting content via newsletter four times a year
Receive exclusive information before all other users