【C++】使用標準C++簡單的解析xml中的信息

簡單實現瞭解析xml其中的標籤,不需要依賴複雜的xml解析器。

1、例如以下xml格式數據:

<?xml version="1.0" encoding="utf-8"?>
<update>
  <descriptions>
    <description>MG-APP will be updated automatically\n</description>
  </descriptions>
  <files>
  <file ver=    "20200529" path=    "1"/>
  <file ver="20200529" path="2"/>
  <file ver = "20200529" path = "3"/>
  <file ver = "20200529" path="MG_APP.exe"/>
  <file ver="20200529" path="images\splash_logo.jpg"/>
  </files>
</update>

2、解析C++代碼:

#include<string>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

// <file ver="20200529" path="2"/> Parse one item,such as "ver"
void paraseLabel(const char *ch, const char *label, char *var)
{
	char buff[1024] = { 0 };
	strcpy_s(buff, ch);
	// find ver
	char *pStart = NULL, *pEnd = NULL;
	pStart = strstr(buff, label);
	// find first =
	pStart = strstr(pStart, "=");
	// find first "
	pStart = strstr(pStart, "\"");
	pStart += 1;
	// find second "
	pEnd = strstr(pStart, "\"");
	*pEnd = '\0';
	// copy ver
	strcpy_s(var, strlen(pStart) + 1, pStart);
}

int main()
{
	// read file
	ifstream getfile;
	char buff[1024] = { 0 };
	char *p = NULL;
	getfile.open("D:/qupdater.xml");
	while (!getfile.eof())
	{
		getfile.getline(buff, 1024);
		cout << buff << endl;
		p = strstr(buff, "<file ");// <file ver="20200529" path="2"/> find "<file" as Start marker
		if (p) {
			char version[512] = { 0 }, filepath[512] = { 0 };
			paraseLabel(buff, "ver", version);
			paraseLabel(buff, "path", filepath);
			cout << version << "->" << filepath << endl;
		}
	}
	getfile.close();
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章