加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

libxml2 简单操作

发布时间:2020-12-15 23:11:12 所属栏目:百科 来源:网络整理
导读:由于公司的配置文件用到了xml,而公司封装了的函数绑定了很多相关的类,我决定自己从头开始研究xml相关的操作,再进行封装。 第一步下载libxml并编译 http://xmlsoft.org/downloads.html ftp://xmlsoft.org/libxml2/ ./configure make make install 移植可能

由于公司的配置文件用到了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 %sn",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请及时的告诉我,谢谢。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读