本帖最后由 Panel 于 2023-12-2 21:17 编辑
最近在温习cpp 11的基础写的,只支持不重复元素的解析
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>Java Programming</title>
<author>John Smith</author>
<publication_year>2020</publication_year>
</book>
</library>
#include <iostream>
#include <fstream>
using namespace std;
string findValue(const string& dst,const string& key)
{
string keyend = R"(</)" + key;
string keysymbol = key + R"(>)";
int keypos = dst.find(keyend);
int startpos = dst.find(keysymbol) + keysymbol.length();
int endpos = keypos - startpos ;
return dst.substr(
startpos,
endpos
);
}
int main()
{
ifstream inputfile("1.xml", ios::binary);
inputfile.seekg(0, ios::end);
streampos filesize = inputfile.tellg();
inputfile.seekg(0, ios::beg);
char* readbuf = new char[filesize];
inputfile.read(readbuf, filesize);
string library_value = findValue(readbuf, "library");
string book_value = findValue(readbuf,"book");
string title_value = findValue(readbuf, "title");
string author_value = findValue(readbuf, "author");
string publication_year_value = findValue(readbuf, "publication_year");
delete[] readbuf;
cout << "library_value:" << library_value << endl;
cout << "book_value:" << book_value << endl;
cout << "title_value:" << title_value << endl;
cout << "author_value:" << author_value << endl;
cout << "publication_year_value:" << publication_year_value << endl;
cout << endl;
}
|