使用libxml2读取文件解析xml

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml2/libxml/parser.h>


int main(int argc, char* argv[])
{
    FILE* pfile = fopen("sample.xml", "rb");
    int ret = fseek(pfile, 0, SEEK_END);
    unsigned int udwDatalen = ftell(pfile);
    printf("len: %d.\n", udwDatalen);


    char* pdata = (char *)malloc(udwDatalen);
    ret = fseek(pfile, 0, SEEK_SET);
    size_t nread = fread(pdata, 1, udwDatalen, pfile);
    printf("read len: %d.\n", nread);
    printf("data: %s.\n", pdata);


#if 1
    xmlDocPtr pDoc = NULL;
    pDoc = xmlReadMemory(pdata, udwDatalen, NULL, NULL, XML_PARSE_NOBLANKS);
    if (NULL == pDoc)
    {
        fprintf(stderr,"Document not parsed successfully. \n");
        return -1;
    }


    xmlNodePtr pRoot = NULL;
    pRoot = xmlDocGetRootElement(pDoc);
    if (NULL == pRoot)
    {
        fprintf(stderr,"empty document\n");
        xmlFreeDoc(pDoc);
        return -1;
    }


    printf("%s\n", pRoot->name);
#endif
    return 0;
}

你可能感兴趣的:(xml,File,null,include)