使用boost c++解析XML

Parsing XML using boost c++

本文关键字:XML 解析 c++ boost 使用      更新时间:2023-10-16

我有一些XML,如下所示:

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

我试着只打印动物的名字(鲨鱼)。我正在使用boost,所以我尝试了以下代码:

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;
}

但它只打印鲨鱼蓝色。我不确定问题出在哪里,也找不到好的例子。有人能提供一些建议吗?

xml必须只有一个根对象。。。你有2个……试试这样的东西:

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

令我惊讶的是,PugiXML开箱即用地支持它:

#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 << "DONEn";
}

打印

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