/*解析XML中的字符串数据*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct s_girl
{
char name[101]; //姓名
int age; //年龄
char sc[101]; //身材
char yz[101]; //样子
};
/*通过解析得到每个有用的信息,姓名年龄
sXMLbuffer是传入的字符串
XMLname是没个信息的名称如:name,age
outcalue是最后获取信息的地址
*/
int GetXMLbuffer(const char *sXMLbuffer,const char *XMLname,char *outvalue);
//将获取的信息放到结构体中
void GetXMLValue(const char *sXML2buffer,struct s_girl *pt);
int main()
{ struct s_girl girl;
char strXMLbuffer[301];
memset(strXMLbuffer,0,sizeof(strXMLbuffer));
strcpy(strXMLbuffer,"<name>西施</name><age>18</age><sc>火辣</sc><yz>漂亮</yz>");//将需要解析的字符串放到buffer中
GetXMLValue(strXMLbuffer,&girl);
printf("name=%s,age=%d,sc=%s,yz=%s",girl.name,girl.age,girl.sc,girl.yz);
return 0;
}
int GetXMLbuffer(const char *sXMLbuffer,const char *XMLname,char *outvalue)
{
char bname[51];
char ename[51];
memset(bname,0,sizeof(bname));
memset(ename,0,sizeof(ename));
sprintf(bname,"<%s>",XMLname); //将变量名写到一个字符串中
sprintf(ename,"</%s>",XMLname);
char *start=NULL;
char *end=NULL;
/*
strstr()函数用来检索子串在字符串中首次出现的位置,其原型为:
char *strstr( char *str, char * substr );str 是父串,substr为子串
*/
start=strstr(sXMLbuffer,bname);//例如那么的地址
end=strstr(sXMLbuffer,ename);///name的地址
if(start ==NULL ||end ==NULL)
{
return -1;
}
strncpy(outvalue,start+strlen(bname),end-start-strlen(bname));
//outvalue就是需要的值,start+strlen(bname)可以定位比如西施的地址,end-start-strlen(bname),西施这个词占用的地址大小
return 0;
}
void GetXMLValue(const char *sXML2buffer,struct s_girl *pt)
{
memset(pt,0,sizeof(struct s_girl));
GetXMLbuffer(sXML2buffer,"name",pt->name);
char str[10];
GetXMLbuffer(sXML2buffer,"age",str);
pt->age=atoi(str);
GetXMLbuffer(sXML2buffer,"sc",pt->sc);
GetXMLbuffer(sXML2buffer,"yz",pt->yz);
}