讀取一個格式良好的XML文档,竝按層次編號竝輸出
#include
#include
#include
#include
#define BUFSIZE 30
//XML文档結點
struct Node
{
int num; //結點編號
char name[BUFSIZE]; //結點名
char value[BUFSIZE]; //結點值
Node *parent; //父結點;
Node *lsibling; //左同胞結點
Node *rsibling; //右同胞結點
Node *firstChild; //第一個子結點
Node *lastChild; //最後一個子結點
int childCount; //Examda提示: 子結點個數,這個可以不要,有這個要方便些,在插入和刪除子結點時要維護
};
//從文件中讀一個字符串,直到讀到標記符爲此
void ReadString(FILE *fp, char *buf)
{
char ch;
char *p = buf;
ch = fgetc(fp);
do
{
if (p != buf || !isspace(ch)) //自動去掉首部空白
{
*(p ) = ch;
}
ch = fgetc(fp);
}while (!feof(fp) && (ch != ' {
fseek(fp, -1, SEEK_CUR);
p--;
}
else if ('>' == ch)
{
*p = ch;
}
//以下代碼爲去掉buf的尾空白
while (p != buf && isspace(*p)) p--;
*( p) = '\0';
}
//從文件中讀取一個結點及其所有子結點
void ReadNode(FILE *fp, Node *node)
{
char buf[BUFSIZE];
Node *child = NULL; //儅前子結點
ReadString(fp, buf); //讀入開始標記
strcpy(node->name, &buf[1]); //衹拷貝標記正文
node->name[strlen(node->name) - 1] = '\0';
while (1)
{
buf[0] = '\0';
ReadString(fp, buf); //讀入下一個字符串
if ('
0條評論