c - 读取 XML 文件并使用 C 打印标签

标签 c arrays string file

有一个 XML 文件,我必须识别、存储和打印其中存在的唯一标签。

示例 XML 文件:

<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

我需要将 note、to、from、heading、body 等标签存储在一个数组中,然后打印出来。

下面是我试过的代码,但在检查和删除结束标记中的 / 以识别重复标记时遇到问题。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*Max number of characters to be read/write from file*/
#define MAX_CHAR_FOR_FILE_OPERATION 1000000 

int read_and_show_the_file()
{  
   FILE *fp;
   char text[MAX_CHAR_FOR_FILE_OPERATION];
   int i;

   fp = fopen("/tmp/test.txt", "r");

  if(fp == NULL)
   {
      printf("File Pointer is invalid\n");
      return -1;
   }
   //Ensure array write starts from beginning
   i = 0;

   //Read over file contents until either EOF is reached or maximum     characters is read and store in character array
   while( (fgets(&text[i++],sizeof(char)+1,fp) != NULL) && (i<MAX_CHAR_FOR_FILE_OPERATION) ) ; 
   const char *p1, *p2, *temp;
   temp = text;

   while(p2 != strrchr(text, ">"))
   {
       p1 = strstr(temp, "<");
       p2 = strstr(p1, ">");
       size_t len = p2-p1;
       char *res = (char*)malloc(sizeof(char)*(len));
       strncpy(res, p1+1, len-1);
       res[len] = '\0';
       printf("'%s'\n", res);

       temp = p2 + 1;
   }

   fclose(fp);

   return 0;
}

main()
{
   if( (read_and_show_the_file()) == 0)
   {
      printf("File Read and Print is successful\n");
   }
   return 0;
}  

我还尝试了 strcmp 检查 if(strcmp(res[0],"/")==0) 的值来检查结束标记,但没有工作,显示段错误. C 上没有示例。请查看并提出建议。

下面是输出:

'note'
'to'
'/to'   //(Want to remove these closing tags from output)
'from'
'/from' //(Want to remove these closing tags from output)
 and so on..

段错误也发生了。

最佳答案

这仅解决了您问题中的一个段错误:

你必须给strcmp提供字符串,不能只给字符(res[0])。但是既然你不需要比较字符串,为什么不只比较第一个字符 (res[0]=='/')?

关于c - 读取 XML 文件并使用 C 打印标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43061404/

相关文章:

Java - 提取特殊字符和单词之间的文本

c - C语言打印文件大小和时间

c++ - 多个 LD_REPLOAD 共享变量

python - 如何在 python 中将 2D 数组 reshape 为 1D 数组?

arrays - 使用Golang修改xml文件中的数据

c++ - 无法弄清楚为什么我的程序在条件不为真时执行 if 语句(数组)

c++ - obj 模型加载纹理坐标和顶点位置未正确加载

c - 如何创建 "C single-line comment"宏

c - 字符串打印额外值 C 编程

python - 迭代字符串追加的时间复杂度实际上是 O(n^2) 还是 O(n)?