您的位置:首页 > 其它

libxml2 的一些用法

2015-06-30 23:07 309 查看
0. libxml2 是个跨平台的C库,用于操作xml文件。API Reference

1. 结构体:

/*文档结构体*/
typedef xmlDoc *xmlDocPtr;

/*节点结构体*/
typedef struct _xmlNode xmlNode;
typedef xmlNode *xmlNodePtr;
struct _xmlNode {
void           *_private;    /* application data */
xmlElementType   type;    /* type number, must be second ! */
const xmlChar   *name;      /* the name of the node, or the entity */
struct _xmlNode *children;    /* parent->childs link */
struct _xmlNode *last;    /* last child link */
struct _xmlNode *parent;    /* child->parent link */
struct _xmlNode *next;    /* next sibling link  */
struct _xmlNode *prev;    /* previous sibling link  */
struct _xmlDoc  *doc;    /* the containing document */

/* End of common part */
xmlNs           *ns;        /* pointer to the associated namespace */
xmlChar         *content;   /* the content */
struct _xmlAttr *properties;/* properties list */
xmlNs           *nsDef;     /* namespace definitions on this node */
void            *psvi;    /* for type/PSVI informations */
unsigned short   line;    /* line number */
unsigned short   extra;    /* extra data for XPath/XSLT */
};

其他API:
xmlChildElementCount/*获取节点的子节点个数*/
/*转码API*/
#include "iconv.h"
int iConvert(const char *from_code, const char *to_code, const char *from_str, size_t f_len, char * to_str, size_t t_len )
{
iconv_t cd;
size_t ret;
cd = iconv_open( to_code, from_code);
if ( cd == (iconv_t)-1 ) {
perror("iconv open error\n");
return -1;
}
ret = iconv( cd, &from_str, &f_len, &to_str, &t_len );
if ( ret == (size_t)-1 )
{
perror("iconv error\n");
iconv_close(cd);
return -1;
}
iconv_close(cd);
return ret;
}


2.读取:

xmlDocPtr doc = xmlReadFile("file.xml", NULL, 0)
/*or*/
xmlDocPtr doc = xmlParseFile("file.xml");


3. 遍历:

/*各层兄弟节点的保存顺序与文件的排列顺序不能确保一致*/
/*libxml的内部字节编码是utf-8,所以如果节点内容是gbk中文,获取时需要用iconv进行转码*/
/* root */
xmlNodePtr cur = xmlDocGetRootElement(doc);
/* children & sibling */
cur = cur->children; /*or xmlFirstElementChild 可以跳过text节点*/
while( cur ) {
if ( xmlStrcmp(cur->name, BAD_CAST("nodename")) == 0 ) {
/*read property*/
char* p_value = xmlGetProp(cur, BAD_CAST("propername"));
/*read content*/
char* n_value = xmlNodeGetContent(cur);
/*convert encode if needed*/
ret = iConvert( "utf-8", "GBK", n_value, xmlStrlen(n_value), outbuffer, outlen);
...
/*free is needed*/
xmlFree(p_value);
xmlFree(n_value);
}
cur = cur->next; /*or xmlNextElementSibling*/
}
xmlFree(doc);


4. 查找:

  1. 如果只查找结果项只有一个,可以通过自行遍历进行查找节点;
  2. 有多个节点匹配,可以通过 xmlXPathEval* 查找节点集;

5. 修改与保存:以后用到再补充……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: