How can I read an XML file into a buffer in C?

后端 未结 8 821
逝去的感伤
逝去的感伤 2021-02-01 11:03

I want to read an XML file into a char *buffer using C.

What is the best way to do this?

How should I get started?

8条回答
  •  野的像风
    2021-02-01 11:30

    And if you want to parse XML, not just reading it into a buffer (something which would not be XML-specific, see Christoph's and Baget's answers), you can use for instance libxml2:

    #include 
    #include 
    #include 
    
    int main(int argc, char **argv) {
       xmlDoc *document;
       xmlNode *root, *first_child, *node;
       char *filename;
    
       if (argc < 2) {
         fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
         return 1;
       }
       filename = argv[1];
    
      document = xmlReadFile(filename, NULL, 0);
      root = xmlDocGetRootElement(document);
      fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
      first_child = root->children;
      for (node = first_child; node; node = node->next) {
         fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
      }
      fprintf(stdout, "...\n");
      return 0;
    }
    

    On an Unix machine, you typically compile the above with:

    % gcc -o read-xml $(xml2-config --cflags) -Wall $(xml2-config --libs) read-xml.c
    

提交回复
热议问题