首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串提升read_xml不读取xml格式

从字符串提升read_xml不读取xml格式
EN

Stack Overflow用户
提问于 2014-02-18 14:29:58
回答 1查看 6.4K关注 0票数 1

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

代码语言:javascript
复制
std::stringstream ss;
ss << "<?xml ?><root><test /></root>";
boost::property_tree::ptree pt;
boost::property_tree::xml_parser::read_xml( ss, pt);

结果:

代码语言:javascript
复制
pt {m_data="" m_children=0x001dd3b0 }

在我使用这个xml代码的字符串之前:

代码语言:javascript
复制
<?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没有任何效果。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-18 15:22:12

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

请考虑这个例子:

代码语言:javascript
复制
#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;
}

它会打印:

代码语言:javascript
复制
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属性树库没有完全记录其功能,但是使用Boost解析XML的一个很好的指南是http://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21856831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档