C语⾔解析XML中的数据
#include <stdio.h>
#include <string.h>
#include "redmaple.h" //⾃定义头⽂件
struct st //结构体st
{
char name[40];
int age;
int height;
double weight;
char sc[20];
};
ReadXML(char*XMLstr,struct st *std)//解析XML
{
char string[50];
memset(string,0,sizeof(string));
int i=0,len,t=0;
while(XMLstr[i]!='\0')//只要XML没到尾
{
if(XMLstr[i]=='>'&& XMLstr[i+1]!='<')//获取XML中的数据,⼀定是中间的数据,⽽不是两端XML中的空值{
i++;len=0;
while(XMLstr[i]!='<'&& XMLstr[i]!='\n')
{
string[len]=XMLstr[i];
len++;i++;
}
switch(t)
{
case(0):strcpy(std->name,string);break;
case(1):{
int j;
double sum=0;
for(j=0;j<=len-1;j++)
{
sum +=(string[j]-48)*POW(10,len-j-1);
}
std->age =(int)sum;
break;
}
case(2):{
int j;
double sum=0;
for(j=0;j<=len-1;j++)
{
sum +=(string[j]-48)*POW(10,len-j-1);
}
std->height =(int)sum;
break;
}
case(3):{
int j=0,dian=0;
double sum=0;
while(string[dian]!='.')
{
dian++;
}
for(j=0;j<dian;j++)
{
sum +=(string[j]-48)*POW(10,dian-j-1);
}
for(j=dian+1;j<len;j++)
for(j=dian+1;j<len;j++)
{
sum +=(string[j]-48)*POW(10,dian-j);
}
std->weight = sum;
break;
}
case(4):strcpy(std->sc,string);break;
}
memset(string,0,sizeof(string));
t++;
}
i++;
}
}
int main()
{
FILE *fp;
if((fp =fopen("","r"))==0)
{
printf("open failed!\n");
}
else
{
struct st std;
char XMLstring[100];
int i=0;
for(i=0;i<5;i++)
{
memset(XMLstring,100,sizeof(XMLstring));
fgets(XMLstring,100,fp);
ReadXML(XMLstring,&std);
printf(" name:%12s\n age:%13d\n height:%10d\n weight:%10.2lf\n "\
"sc:%14s\n\n",std.name,std.age,std.height,std.weight,std.sc);
c语言struct头文件}
}
}
redmaple.c 头⽂件内容
#include "redmaple.h"
#include <string.h>
#include <stdio.h>
double POW(int x,int y)//求x的y次幂
{
if(y>0)
{
if(x ==0)
{
return0;
}
else
{
int i;
int A = x;
for(i=1;i<y;i++)
{
A *= x;
}
return(double)A;
}
}
else if(y<0)
{
if(x==0)
{
return0;
}
else
{
int i;
int A = x;
for(i=1;i<y*(-1);i++)
{
A *= x;
}
return1.0/A;
}
}
else
{
return1;
}
}
这个READXML只能对特定的结构体进⾏读取XML数据,不能对任意的结构体进⾏运作,还有待改善实验结果
XML编码
获取编码内的数据,然后存储进结构体内,最后把结构体内的数据都输出出来
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论