libxml2的简单使用

编程

libxml2是处理xml的C库。网上很多加载,解析xml的参考,但是却没有这样的参考:从解析,修改某个node,再保存的完整过程。

代码

#include <stdio.h>

#include <stdlib.h>

#include <libxml/parser.h>

#include <libxml/xpath.h>

void parse(char *file) {

xmlChar *text;

xmlDocPtr doc;

xmlXPathContextPtr ctxt;

xmlXPathObjectPtr obj;

xmlNodePtr cur;

char name[256];

int size;

xmlChar *new_xml = NULL;

doc = xmlParseFile(file);

if (doc == NULL ) {

fprintf(stderr,"failed to parse file "%s".

", file);

return;

}

ctxt = xmlXPathNewContext(doc);

if (ctxt == NULL) {

fprintf(stderr,"failed to alloc ctxt

");

return;

}

obj = xmlXPathEval(BAD_CAST "/network/name", ctxt);

cur = obj->nodesetval->nodeTab[0]->children;

if (!cur || cur->type != XML_TEXT_NODE || cur->next != NULL) {

fprintf(stderr,"failed to search name

");

return;

}

text = xmlNodeGetContent(cur);

printf("orig name: %s

", text);

sprintf(name, "%s-v2", text);

xmlNodeSetContent(cur, (const xmlChar *)name);

xmlDocDumpMemory(doc, &new_xml, &size);

printf("new xml size: %d

", size);

printf("new xml: %s

", new_xml);

xmlFreeNode(cur);

xmlXPathFreeObject(obj);

xmlXPathFreeContext(ctxt);

xmlFreeDoc(doc);

return;

}

int main(int argc, char **argv) {

if (argc < 2) {

fprintf(stderr, "Usage: %s filename

", argv[0]);

return -1;

}

parse(argv[1]);

return 0;

}

编译

gcc -Wall -g -I /usr/include/libxml2 -lxml2 parse.c -o parse

示例

xml file

<network>

<name>test</name>

</network>

parse ./test.xml

参考

  • http://www.xmlsoft.org/html/
  • http://www.hyuuhit.com/2018/12/03/libxml2/
  • http://xmlsoft.org/tutorial/xmltutorial.pdf

以上是 libxml2的简单使用 的全部内容, 来源链接: utcz.com/z/515503.html

回到顶部