user5123269
user5123269

Reputation:

pugixml parser getting element value

I have XML with structure like this:

 <info>
     <students>
         <student>
             <name>John</name>
             <street>
                 <name>abcdef</name>
                 <number>55</number>
             </street>
         </student>
     </students>  
  </info>

And I correctly print value of name tag with this code

pugi::xml_node students = doc.child("info").child("students");

for (pugi::xml_node student = students.child("name"); student; student= student.next_sibling("student"))
    {
        std::cout << "name '" << student.child_value("name") << "'\n";
    }

But, I also need to print values of name & number - tags inside street and I could not succeed.

Here is code to display values from that two tag elements:

pugi::xml_node student = doc.child("students").child("student");

for (pugi::xml_node street = student.child("street"); street; street = student.next_sibling("street"))
    {
        std::cout << "name '" << student.child_value("name") << "'\n";
        std::cout << "number '" << student.child_value("number") << "'\n";
    }

but it shows nothing.

Anyone knows what may be wrong?

Upvotes: 0

Views: 1129

Answers (1)

Kvothe
Kvothe

Reputation: 1837

In your loop you still have student but it needs to be street

for (pugi::xml_node street = student.child("street"); street; street = street.next_sibling("street"))
{
    std::cout << "name '" << street.child_value("name") << "'\n";
    std::cout << "number '" << street.child_value("number") << "'\n";
}

If you compare my loop to the second one you posted in your question you will see that I have replaced student with street in several places. I guess you copy pasted your first loop but forgot to change those values.

I see you changed the code in your question - but it still needs to be street = street.next_sibling('street') to loop through all the streets for a particular student.

Addition

Just noticed - your code to get the student node is missing the info node

You have:

`pugi::xml_node student = doc.child("students").child("student");`

It should be:

`pugi::xml_node student = doc.child("info").child("students").child("student");`

Upvotes: 1

Related Questions