c++ - XPATH在C++ Boost中使用

标签 c++ c++11 boost c++14

是否有任何类似于C#(SelectSingleNode()等)的XPATH使用方式。

我正在尝试使用boost::property_tree::ptree,但它与C#/ VBA XML解析有点不同。

<?xml version="1.0"?>
<Classes>

  <Class name="first">
   <Elements>
    <ElementA>aa</ElementA>
    <ElementB>bb</ElementB>
   </Elements>
  </Class>

  <Class name="second">
   <Elements>
    <ElementA>cc</ElementA>
    <ElementB>dd</ElementB>
   </Elements>
  </Class>

  <Class name="third">
   <Elements>
    <ElementA>ee</ElementA>
    <ElementB>ff</ElementB>
   </Elements>
  </Class>

</Classes>

我必须迭代这种配置,并根据Classes / Class [@name]属性选择子树。

我如何用ptree做到这一点。

最佳答案

没有几个很好的链接来了解ptree的数据结构,并且从那里很容易。

从这里开始,Boost property tree : how to get child of child tree with a xml file

然后在这里https://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/

#include <iostream>
#include <string>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <fstream>

int main()
{
  std::string xml = R"(<?xml version="1.0"?>
<Classes>

  <Class name="first">
   <Elements>
    <ElementA>aa</ElementA>
    <ElementB>bb</ElementB>
   </Elements>
  </Class>

  <Class name="second">
   <Elements>
    <ElementA>cc</ElementA>
    <ElementB>dd</ElementB>
   </Elements>
  </Class>

  <Class name="third">
   <Elements>
    <ElementA>ee</ElementA>
    <ElementB>ff</ElementB>
   </Elements>
  </Class>

</Classes>)";

  //std::cout << xml;

  using boost::property_tree::ptree;
  std::stringstream ss(xml);
  ptree p;
  read_xml(ss,p);

  std::ostringstream subTree;
  BOOST_FOREACH( ptree::value_type const& v, p.get_child("Classes") )
  {   
      //if(v.second.get<std::string>("<xmlattr>.name") ==  "first") 
       write_xml(subTree, v.second);
       std::cout << subTree.str();
       std::cout << "\n====================\n";

  }
}

关于c++ - XPATH在C++ Boost中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55434806/

相关文章:

c++ - 在适用于 Linux 的 Eclipse (C++) 中链接到 matlab 库

c++ - 避免警告 : operation on ‘count’ may be undefined [-Wsequence-point]

C++线程开销

c++ - 在 C++11 STL 之前模拟大括号列表初始化

c++ - QSharedPointer VS std::tr1::shared_ptr VS boost::tr1::shared_ptr

python - 将 Boost Python 与 shared_ptr<const T> 一起使用

C++ 唯一元素的数量

c++ - Visual Studio 2013 CTP 是否支持非整数类型的类内静态常量初始值设定项?

c++ - BOOST - 类模板队列

c++ - 拒绝来自主机的连接