来自stringstream的boost read_xml不读取xml格式

时间:2014-02-18 14:29:58

标签: c++ xml visual-studio-2012 boost boost-propertytree

我想用xml中的数据填充boost :: property_tree :: ptree, xml格式是一个字符串,我传递给stringstream,然后我尝试 用read_xml读取它,但是当我查看对象时,ptree数据为null或为空 在调试时,我的代码:

std::stringstream ss;
ss << "<?xml ?><root><test /></root>";
boost::property_tree::ptree pt;
boost::property_tree::xml_parser::read_xml( ss, pt);

结果:

pt {m_data="" m_children=0x001dd3b0 }

之前我有一个包含此xml代码的字符串:

<?xml version="1.0"?><Response Location="910" RequesterId="12" SequenceNumber="0">
<Id>1</Id>
<Type>P</Type>
<StatusMessage></StatusMessage>
<Message>Error</Message>
</Response>

但是使用带有c ++的visual studio没有任何效果。

1 个答案:

答案 0 :(得分:2)

没有与根节点关联的数据,因此m_data为空,但有一个子节点( test )和m_children != nullptr

请考虑这个例子:

#include <sstream>
#include <string>
#include <boost/property_tree/xml_parser.hpp>

int main()
{
  std::stringstream ss;
  ss << "<?xml ?><root><test /></root>";
  boost::property_tree::ptree pt;
  boost::property_tree::xml_parser::read_xml(ss, pt);

  // There is no data associated with root node...
  std::string s(pt.get<std::string>("root"));
  std::cout << "EXAMPLE1" << std::endl << "Data associated with root node: " << s << std::endl;

  // ...but there is a child node.
  std::cout << "Children of root node: ";
  for (auto r : pt.get_child("root"))
    std::cout << r.first << std::endl;

  std::cout << std::endl << std::endl;

  std::stringstream ss2;
  ss2 << "<?xml ?><root>dummy</root>";
  boost::property_tree::xml_parser::read_xml(ss2, pt);

  // This time we have a string associated with root node
  std::string s2(pt.get<std::string>("root"));
  std::cout << "EXAMPLE2" << std::endl << "Data associated with root node: " << s2 << std::endl;

  return 0;
}

它会打印:

EXAMPLE1
Data associated with root node: 
Children of root node: test

EXAMPLE2
Data associated with root node: dummy

http://coliru.stacked-crooked.com/a/34a99abb0aca78f2)。

Boost propertytree库没有完整记录其功能,但使用Boost解析XML的一个很好的指南是http://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/