-1
我想解析C++中的XML文檔,並能夠識別特定標籤中存在哪些文本。我已經檢查過像TiyXML和PugiXML這樣的解析器,但它們都沒有分別識別標籤。我怎樣才能做到這一點?解析XML文檔
我想解析C++中的XML文檔,並能夠識別特定標籤中存在哪些文本。我已經檢查過像TiyXML和PugiXML這樣的解析器,但它們都沒有分別識別標籤。我怎樣才能做到這一點?解析XML文檔
使用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.
}
}
}
要與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());
編寫的XML解析器不是一件容易的事。 – DeiDei
你嘗試過那種方法沒有奏效? – Galik
請詳細說明任務,您想要存檔什麼?解析xml文件時,您需要知道具有所有可能屬性的方案。可用的XML解析器中缺少什麼? – paweldac