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\".\n", file);
return;
}
ctxt = xmlXPathNewContext(doc);
if (ctxt == NULL) {
fprintf(stderr,"failed to alloc ctxt\n");
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 \n");
return;
}
text = xmlNodeGetContent(cur);
printf("orig name: %s\n", text);
sprintf(name, "%s-v2", text);
xmlNodeSetContent(cur, (const xmlChar *)name);
xmlDocDumpMemory(doc, &new_xml, &size);
printf("new xml size: %d\n", size);
printf("new xml: %s\n", 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\n", 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
来源:oschina
链接:https://my.oschina.net/u/2475751/blog/3235703