使用libxml2解析xml

book.xml

<?xml version="1.0" encoding="UTF-8" ?>
<books>
    <book2>
        <name id="1">c primer plus111</name>
        <author>unknow author</author>
        <date>unknow date</date>
    </book2>
    <book111111>
        <name>c++ 21天入门到精通</name>
        <author>未知作者</author>
        <date>未知日期</date>
    </book111111>
</books>

  

//
// Created by gxf on 2020/2/6.
//

#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
//#include <libxml/tree.h>

void println(char *s);

typedef struct {
    char *name;
    char *author;
    char *date;
}book;

void printBook(book book1);

int main() {
    xmlDocPtr bookDocPtr;
    xmlNodePtr booksNodePtr;
    char *bookDocName = "/Users/gxf/CLionProjects/untitled/books.xml";

    // libxml默认将各个节点间的空格当作一个节点
    xmlKeepBlanksDefault(0);
    bookDocPtr = xmlParseFile(bookDocName);
    if (bookDocPtr == NULL) {
        fprintf(stderr, "xmlReadFile fail");
        exit(1);
    }
    book onebook;

    // root node
    booksNodePtr = xmlDocGetRootElement(bookDocPtr);

    // book node
    xmlNodePtr bookNodePtr = booksNodePtr->children;
    while (bookNodePtr) {
        // name
        xmlNodePtr namePtr = bookNodePtr->children;
//        println(xmlNodeGetContent(namePtr));
        onebook.name = xmlNodeGetContent(namePtr);

        // author
        xmlNodePtr authorPtr = namePtr->next;
//        println(xmlNodeGetContent(authorPtr));
        onebook.author = xmlNodeGetContent(authorPtr);

        // date
        xmlNodePtr datePtr = authorPtr->next;
//        println(xmlNodeGetContent(datePtr));
        onebook.date = xmlNodeGetContent(datePtr);

        printBook(onebook);


        bookNodePtr = bookNodePtr->next;
    }

    return 0;
}

void println(char *s) {
    printf("%s\n", s);
}

void printBook(book book1) {
    printf("name: %s\n", book1.name);
    printf("author: %s\n", book1.author);
    printf("date: %s\n", book1.date);
}

  cmakelist

# libxml2
include_directories(/usr/local/include/libxml2)
link_libraries(xml2)
add_executable(libxml2-demo libxml2-demo.c)

  

posted on 2020-02-06 17:48  luckygxf  阅读(1378)  评论(0编辑  收藏  举报

导航