Łukasz Przeniosło
Łukasz Przeniosło

Reputation: 2949

How to read through nodes using pugixml?

I have just downloaded the pugixml library and I am trying to adapt it to my needs. It is mostly oriented for DOM style which I am not using. The data I store looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<profile>
    <points>
        <point>
            <index>0</index>
            <x>0</x>
            <y>50</y>
        </point>
        <point>
            <index>1</index>
            <x>2</x>
            <y>49.9583</y>
        </point>
        <point>
            <index>2</index>
            <x>12</x>
            <y>50.3083</y>
        </point>
     </points>
</profile>

Pugixml guide says:

It is common to store data as text contents of some node - i.e. This is a node. In this case, node does not have a value, but instead has a child of type node_pcdata with value "This is a node". pugixml provides child_value() and text() helper functions to parse such data.

But I am having problem with using those methods, I am not getting the node values out.

#include "pugixml.hpp"

#include <string.h>
#include <iostream>

int main()
{
    pugi::xml_document doc;
    if (!doc.load_file("/home/lukasz/Programy/eclipse_linux_projects/xmlTest/Debug/pidtest.xml"))
        return -1;

    pugi::xml_node points = doc.child("profile").child("points");

    for (pugi::xml_node point = points.first_child(); point; point = points.next_sibling())
    {
        // ?
    }


    return 0;
}

How to read out the index, x and y values inside of the for? I Would aprichiate all help.

Upvotes: 2

Views: 4481

Answers (1)

sehe
sehe

Reputation: 392833

There are several ways, documented in the quickstart page:

May I suggest Xpath?

#include <pugixml.hpp>
#include <iostream>

int main()
{
    pugi::xml_document doc;

    if (doc.load_file("input.txt")) {
        for (auto point : doc.select_nodes("//profile/points/point")) {
            point.node().print(std::cout, "", pugi::format_raw);
            std::cout << "\n";
        }
    }
}

Prints

<point><index>0</index><x>0</x><y>50</y></point>
<point><index>1</index><x>2</x><y>49.9583</y></point>
<point><index>2</index><x>12</x><y>50.3083</y></point>

Upvotes: 5

Related Questions