1.源码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main()
{
//定义文档和节点指针
xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
doc->encoding = BAD_CAST strdup("UTF-8");
xmlNodePtr root = xmlNewNode(NULL, BAD_CAST"root");
//设置根节点
xmlDocSetRootElement(doc, root);
//在根节点直接创建节点
xmlNewTextChild(root, NULL, BAD_CAST"newnode1", BAD_CAST"newnode1 conetent");
xmlNewTextChild(root, NULL, BAD_CAST"newnode2", BAD_CAST"newnode2 conetent");
xmlNewTextChild(root, NULL, BAD_CAST"newnode3", BAD_CAST"newnode3 conetent");
//创建一个节点, 设置其内容和属性, 然后加入根节点
xmlNodePtr node = xmlNewNode(NULL, BAD_CAST"node2");
xmlNodePtr content = xmlNewText(BAD_CAST"NODE CONETENT");
xmlAddChild(root, node);
xmlAddChild(node, content);
//创建一个儿子和孙子节点
node = xmlNewNode(NULL, BAD_CAST"son");
xmlAddChild(root, node);
xmlNodePtr grandson = xmlNewNode(NULL, BAD_CAST"grandson");
xmlAddChild(node, grandson);
//添加属性
xmlNewProp(node, BAD_CAST"attribute", BAD_CAST"yes");
//存储xml文档
int ret = xmlSaveFile("createxml.xml", doc);
if(ret != -1)
{
printf("一个xml文档被创建, 写入%d个字节\n", ret);
}
//释放文档节点动态申请的内存
free((void *)(doc->encoding));
doc->encoding = NULL;
xmlFreeDoc(doc);
return 0;
}
2.编译源码
$ gcc -o SaveXmlFile SaveXmlFile.c -I/usr/local/include/libxml2 -L/usr/local/lib -lxml2
3.运行结果
<?xml version="1.0" encoding="UTF-8"?>
<root><newnode1>newnode1 conetent</newnode1><newnode2>newnode2 conetent</newnode2><newnode3>newnode3 conetent</newnode3><node2>NODE CONETENT</node2><son attribute="yes"><grandson/></son></root>
网友评论