Parmi les nombreuses fonctions de libxml2, se trouve une interface de gestion de liste.
Ci dessous, un exemple d'implémentation
#include <libxml/list.h>
#include <stdio.h>
#include <malloc.h>
struct Record
{
int value;
float val;
} ;
int
walker
(const char *data,
const void *user
)
{
struct Record *element =
(struct Record*
)data;
printf("%i,%f\n", element->value,element->val
);
return (1);
}
static void release
(xmlLinkPtr lk
){
struct Record* el1 =
(struct Record*
)xmlLinkGetData
(lk
);
free
(el1
);
}
void main
(){
struct Record* el1;
int i;
xmlListPtr list;
list = xmlListCreate
((xmlListDeallocator
)release,
NULL);
el1=
(struct Record*
)malloc
(sizeof(struct Record
));
el1->val=
10.
0;
el1->value=
10;
xmlListInsert
(list,el1
);
el1=
(struct Record*
)malloc
(sizeof(struct Record
));
el1->val=
11.
0;
el1->value=
11;
xmlListInsert
(list,el1
);
i = xmlListSize
(list
);
printf("xmlListSize:%i\r\n",i
);
xmlListWalk
(list,
(xmlListWalker
)walker,
NULL);
el1 =
(struct Record*
)xmlLinkGetData
(xmlListEnd
(list
));
xmlListSearch
(list,el1
);
xmlListWalk
(list,
(xmlListWalker
)walker,
NULL);
xmlListClear
(list
);
}
pour une liste chaînée avec mémorisation de la dernière valeur ajoutée, dans cet exemple la valeur de l'élément test2 est initialement fixée à 2 pour être finalement remplacée par 3.
#include <libxml/list.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
struct Record
{
int value;
char name
[6];
} ;
int
walker
(const char *data,
const void *user
)
{
struct Record *record =
(struct Record*
)data;
printf("%s,%i\n",record->name, record->value
);
return (1);
}
static void release
(xmlLinkPtr lk
){
struct Record* record =
(struct Record*
)xmlLinkGetData
(lk
);
free
(record
);
}
static int comp
(const struct Record* data0,
const struct Record* data1
){
return stricmp
(data0->name,data1->name
);
}
void main
(){
struct Record* el1;
int i;
xmlListPtr list;
list = xmlListCreate
((xmlListDeallocator
)release,
(xmlListDataCompare
)comp
);
el1=
(struct Record*
)malloc
(sizeof(struct Record
));
el1->value=
1;
strcpy
(el1->name,
"test1");
xmlListInsert
(list,el1
);
el1=
(struct Record*
)malloc
(sizeof(struct Record
));
el1->value=
2;
strcpy
(el1->name,
"test2");
xmlListInsert
(list,el1
);
el1=
(struct Record*
)malloc
(sizeof(struct Record
));
strcpy
(el1->name,
"test2");
el1->value=
3;
if(xmlListSearch
(list,el1
) ==
NULL)
xmlListInsert
(list,el1
);
else{
xmlListRemoveAll
(list,el1
);
xmlListInsert
(list,el1
);
}
i = xmlListSize
(list
);
printf("xmlListSize:%i\r\n",i
);
xmlListWalk
(list,
(xmlListWalker
)walker,
NULL);
xmlListClear
(list
);
}