2

I have some XML that looks like this:

<animal> 
    <name>shark</name> 
    <color>blue</color>
</animal>
<animal> 
    <name>dog</name> 
    <color>black</color>
</animal>

I'm trying to print only the animal names (shark and dog). I am using boost so I tried the following code:

ptree pt;
boost::property_tree::read_xml("animals.xml", pt);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt.get_child("animal"))
{
    std::cout << v.second.data() << std::endl;
}

But it only prints shark and blue. I'm not sure what the problem is, and I can't find good examples. Can someone offer some advice?

0

2 Answers 2

2

xml has to have only one root object... you have 2.. try something like:

<animals>
  <animal> 
    <name>shark</name> 
    <color>blue</color>
  </animal>
  <animal> 
    <name>dog</name> 
    <color>black</color>
  </animal>
</animals>
Sign up to request clarification or add additional context in comments.

3 Comments

@YoavCohen, then your "XML" parser is working ok... if what you have is something that isn't XML, you can try to cajole it into being xml or maybe your parser has has options to support your scenario... but it would be like if you said your C compiler needs to accept int73_t i = "zebra"; because that is what you are given...
well this is not in my control how many roots this xml(or whatever i got ) has. there is no way to implement a parser for this kind of file?
@YoavCohen absolutely there is a way to implement a parser for that kind of File, but what I would do, would be to set up a stringstream inject a root object tag, then inject your payload then inject a root object close tag, then use the sting from that as your xml object...
1

To my surprise, PugiXML supports it out of the box:

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

int main() {
    pugi::xml_document doc;
    std::ifstream ifs("input.txt", std::ios::binary);

    pugi::xml_parse_result r = doc.load(ifs, pugi::parse_default);

    std::cout << "PARSED " << r.status << " (" << r.description() << "):\n";
    doc.save(std::cout, "  ", pugi::format_default);
    std::cout << "DONE\n";
}

Prints

PARSED 0 (No error):
<?xml version="1.0"?>
<animal>
  <name>shark</name>
  <color>blue</color>
</animal>
<animal>
  <name>dog</name>
  <color>black</color>
</animal>
DONE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.