cpp解析xml文件
本帖最后由 Panel 于 2023-12-2 21:17 编辑### 最近在温习cpp 11的基础写的,只支持不重复元素的解析
```xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>Java Programming</title>
<author>John Smith</author>
<publication_year>2020</publication_year>
</book>
</library>
```
```cpp
#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;
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;
}
```
哦哦,原来如此, 引入了java的包? FruitBaby 发表于 2023-12-2 21:21
引入了java的包?
没有啊,就字符串匹配写的,原生 学习一下 对于重复元素会是什么情况? FelixLee 发表于 2023-12-3 13:03
对于重复元素会是什么情况?
比如出现两个<book>a</book><book>b</book> 感谢发布原创作品,吾爱破解论坛因你更精彩! 学到了 真厉害, 感谢分享源代码
页:
[1]