2016-12-27 119 views
-1

我想解析C++中的XML文档,并能够识别特定标签中存在哪些文本。我已经检查过像TiyXML和PugiXML这样的解析器,但它们都没有分别识别标签。我怎样才能做到这一点?解析XML文档

+5

编写的XML解析器不是一件容易的事。 – DeiDei

+2

你尝试过那种方法没有奏效? – Galik

+1

请详细说明任务,您想要存档什么?解析xml文件时,您需要知道具有所有可能属性的方案。可用的XML解析器中缺少什么? – paweldac

回答

0

使用RapidXml,您可以遍历节点和属性并标识其标签的文本。

#include <iostream> 
#include <rapidxml.hpp> 
#include <rapidxml_utils.hpp> 
#include <rapidxml_iterators.hpp> 

int main() 
{ 
    using namespace rapidxml; 

    file<> in ("input.xml"); // Load the file in memory. 
    xml_document<> doc; 
    doc.parse<0>(in.data()); // Parse the file. 

    // Traversing the first-level elements. 
    for (node_iterator<> first=&doc, last=0; first!=last; ++first) 
    { 
     std::cout << first->name() << '\n'; // Write tag. 

     // Travesing the attributes of the element. 
     for (attribute_iterator<> attr_first=*first, attr_last=0; 
       attr_first!=attr_last; ++attr_first) 
     { 
      std::cout << attr_first->name() << '\n'; // Write tag. 
     } 
    } 
} 
0

要与pugixml得到所有标签名称:

void dumpTags(const pugi::xml_node& node) { 
    if (!node.empty()) { 
    std::cout << node.name() << std::endl; 
    for (pugi::xml_node child=node.first_child(); child; child=child.next_sibling()) 
     dumpTags(child); 
    } 
} 

pugi::xml_document doc; 
pugi::xml_parse_result result = doc.load("<tag1>abc<tag2>def</tag2>pqr</tag1>"); 
dumpTags(doc.first_child());