码迷,mamicode.com
首页 > 其他好文 > 详细

使用libxml2解析xml

时间:2020-02-06 18:09:19      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:name   fprintf   ring   def   book   ocp   led   rar   children   

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)

  

使用libxml2解析xml

标签:name   fprintf   ring   def   book   ocp   led   rar   children   

原文地址:https://www.cnblogs.com/luckygxf/p/12269574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!