【问题标题】:boost read_xml from stringstream does not read xml format从 stringstream 提升 read_xml 不读取 xml 格式
【发布时间】:2014-02-18 14:29:58
【问题描述】:

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

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 没有任何效果。

【问题讨论】:

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


    【解决方案1】:

    没有与根节点关联的数据,因此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 属性树库并未完整记录其功能,但使用 Boost 解析 XML 的一个很好的指南是 http://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多