我的XML文件具有: xml元数据 我正在此文件中搜索标签,并且此标签的开始和结束标签之间的文本必须打印在控制台上。即在这种情况下,我希望将xmlMetadata打印在控制台上。同样,如果它在同一文件中遇到另一个标记,则应在文件中走得更远并再次打印。这是我的代码,但它正在打印整个文件的内容:{ string line="< Package >"; ifstream myfile (xmlFileName); //xmlFileName is xml file in which search is to done if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); std::cout<<line<< endl; } myfile.close(); } else cout << "Unable to open file";}在我的整个xml下面显示:< ? xml version="1.0" ? >< fileStructure >< Main_Package > File_Navigate< /Main_Package >< Dependency_Details >< Dependency > < Package > xmlMetadata < /Package > < Header > xmlMetadata.h < /Header > < Header_path > C:\Dependency\xmlMetadata\xmlMetadata.h < /Header_path > < Implementation > xmlMetadata.cpp < /Implementation > < Implementation_path > C:\Dependency\xmlMetadata\xmlMetadata.cpp < /Implementation_path >< /Dependency >< Dependency > < Package > xmlMetadata1 < /Package > < Header > xmlMetadata1.h < /Header > < Header_path > C:\Dependency\xmlMetadata\xmlMetadata1.h < /Header_path > < Implementation > xmlMetadata1.cpp < /Implementation > < Implementation_path > C:\Dependency\xmlMetadata\xmlMetadata1.cpp < /Implementation_path >< /Dependency >< /Dependency_Details >< /fileStructure > (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 这不是解析XML文件的方式,但是由于您不想使用解析器库,因此此代码可能会让您入门。文件: demo.xml <? xml version="1.0" ?><fileStructure><Main_Package> File_Navigate</Main_Package><Dependency_Details><Dependency> <Package> xmlMetadata </Package> <Header> xmlMetadata.h </Header> <Header_path> C:\Dependency\xmlMetadata\xmlMetadata.h </Header_path> <Implementation> xmlMetadata.cpp </Implementation> <Implementation_path> C:\Dependency\xmlMetadata\xmlMetadata.cpp </Implementation_path></Dependency><Dependency> <Package> xmlMetadata1 </Package> <Header> xmlMetadata1.h </Header> <Header_path> C:\Dependency\xmlMetadata\xmlMetadata1.h </Header_path> <Implementation> xmlMetadata1.cpp </Implementation> <Implementation_path> C:\Dependency\xmlMetadata\xmlMetadata1.cpp </Implementation_path></Dependency></Dependency_Details></fileStructure>该代码的基本思想是,当您读取文件的每一行时,去除开头的空白并将新剥离的字符串存储到tmp中,然后尝试将其与您要使用的标签之一进行匹配寻找。找到开始标记后,继续打印以下行,直到找到结束标记。文件: parse.cpp #include <iostream>#include <string>#include <fstream>using namespace std;int main(){ string line; ifstream in("demo.xml"); bool begin_tag = false; while (getline(in,line)) { std::string tmp; // strip whitespaces from the beginning for (int i = 0; i < line.length(); i++) { if (line[i] == ' ' && tmp.size() == 0) { } else { tmp += line[i]; } } //cout << "-->" << tmp << "<--" << endl; if (tmp == "<Package>") { //cout << "Found <Package>" << endl; begin_tag = true; continue; } else if (tmp == "</Package>") { begin_tag = false; //cout << "Found </Package>" << endl; } if (begin_tag) { cout << tmp << endl; } }} 输出:xmlMetadataxmlMetadata1 (adsbygoogle = window.adsbygoogle || []).push({});
10-08 17:41