[libxml]如何提取属性值

来源:互联网 发布:查淘宝店铺信誉等级 编辑:程序博客网 时间:2024/05/11 14:59

用作例子的xml文件内容如下:

<?xml version="1.0" encoding="ISO-8859-1"?>
<config>
<Attributes>
<avp name="SessionNum" code="200" encrypt="false"/>
</Attributes>
</config>


源码:

#include <stdio.h>
#include <string.h>

#include <libxml2/libxml/parser.h>
#include <libxml2/libxml/tree.h>
#include <libxml2/libxml/xmlmemory.h>

int main(void)
{
xmlDocPtr  doc = NULL;
xmlNodePtr proot = NULL,pfirst = NULL,psecond = NULL;
xmlChar *value = NULL;

xmlKeepBlanksDefault(0);//必须加上,防止程序吧元素前后的空白文本符号当作一个node
doc = xmlReadFile("test.xml","UTF-8",XML_PARSE_RECOVER);//libxml只能解析UTF-8格式数据
if (doc == NULL)
{
printf("error:can't open file!\n");
return ERROR;
}

proot = xmlDocGetRootElement(doc);
if (proot == NULL)
{
printf("error:file is empty!\n");
return ERROR;
}
pfirst = proot->children;


while(pfirst != NULL)
{
if(!xmlStrcmp(pfirst->name,BAD_CAST("Attributes")))
{
psecond = pfirst->children;
while(psecond != NULL)
{
if (!xmlStrcmp(psecond->name,BAD_CAST("avp")))
{
if ((value = xmlGetProp(psecond,BAD_CAST("name"))))
{
printf("name:%s\n",(char *)value);
xmlFree(value);
}
if ((value = xmlGetProp(psecond,BAD_CAST("code"))))
{
printf("code:%s\n",(char *)value);
xmlFree(value);
}
if ((value = xmlGetProp(psecond,BAD_CAST("encrypt"))))
{
printf("encrypt:%s\n",value);
xmlFree(value);
}
psecond = psecond->children;
}
}
}
pfirst = pfirst->next;
}
xmlFreeDoc(doc);
xmlCleanupParser();
xmlMemoryDump();

return OK;
}


测试结果:

name:SessionNum
code:200
encrypt:false

0 0
原创粉丝点击