libxml2 简单操作

由于公司的配置文件用到了xml,而公司封装了的函数绑定了很多相关的类,我决定自己从头开始研究xml相关的操作,再进行封装。


第一步下载libxml并编译

http://xmlsoft.org/downloads.html

ftp://xmlsoft.org/libxml2/


./configure
make
make install

移植可能需要的lib库

/usr/lib/libxml2.so.2.7.8

/usr/lib/opkg/info/libxml2.control

/usr/lib/opkg/info/libxml2.list
/usr/lib/opkg/info/libxml2.postinst
/usr/lib/libxml2.so.2

相关的函数
1 打开xml文件
xmlDoc * doc;
doc = xmlParseFile("tt.xml");

2 保存为xml文件
xmlDoc * doc;
xmlSaveFile("tt.xml",doc);

3 设置root节点
xmlNode * root;
xmlDocSetRootElement(doc,root);

4 获得root节点
root = xmlDocGetRootElement(doc);

5 新增一个节点
xmlNode * node;
node = xmlNewNode(NULL,"node1");

6 删除一个节点
xmlUnlinkNode(node);
xmlFreeNode(node);

7 增加子节点
xmlAddChild(root,node);

8 节点增加属性
xmlNewProp(node,"id","1");

9 节点获得属性
char * str;
str = xmlGetProp(node,"id");

10 节点修改属性
xmlSetProp(node,"100");

11 节点增加content
xmlNewText("hello world");

12 节点修改content
xmlNodeSetContent(node,"hi");

13 节点获得content文本
char * str;
str = xmlNodeGetContent(node);

14 遍历节点
xmlNode * find_node(xmlNode * root,char * str)
{
xmlNode *cur_node = NULL;
xmlNode *tmp_node = NULL;
if ( root == NULL ){
return NULL;
}
for (cur_node = root; cur_node; cur_node = cur_node->next) {
if ( !xmlStrcmp(cur_node->name,BAD_CAST str) ){
return cur_node;
}
tmp_node = find_node(cur_node->children,str);
if ( tmp_node ){
cur_node = tmp_node;
return cur_node;
}
}
return cur_node;
}


xmlNode * select_node(xmlNode * root,char * name,char * attr,char * value)
{
xmlNode * cur_node = NULL;
xmlNode * tmp_node = NULL;
if ( root == NULL ){
return NULL;
}
for ( cur_node = root ; cur_node ; cur_node = cur_node->next ){
if ( !xmlStrcmp(cur_node->name,name) ){
//printf("xmlStrcmp %s\n",cur_node->name);
char * strvalue;
strvalue = xmlGetProp(cur_node,attr);
assert(strvalue);
//find node match value
if ( !xmlStrcmp(strvalue,value) ){
return cur_node;
}
}
tmp_node = select_node(cur_node->children,name,attr,value);
if ( tmp_node != NULL ){
cur_node = tmp_node;
return cur_node;
}
}
return cur_node;

}


代码均经过验证,可以很方便的进行参考,如果发现BUG请及时的告诉我,谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类
XML入门的常见问题(二)
Java对象的强、软、弱和虚引用
JS解析XML文件和XML字符串详解
java中枚举的详细使用介绍
了解Xml格式
XML入门的常见问题(四)
深入SQLite多线程的使用总结详解
PlayFramework完整实现一个APP(一)
XML和YAML的使用方法
XML轻松学习总节篇