使用libxml2解析xml
Posted luckygxf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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 ", s); } void printBook(book book1) { printf("name: %s ", book1.name); printf("author: %s ", book1.author); printf("date: %s ", book1.date); }
cmakelist
# libxml2 include_directories(/usr/local/include/libxml2) link_libraries(xml2) add_executable(libxml2-demo libxml2-demo.c)
以上是关于使用libxml2解析xml的主要内容,如果未能解决你的问题,请参考以下文章
从 XML 声明片段获取 XML 编码:部分内容解析不支持 XmlDeclaration