【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;
}
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页