当前位置: 代码迷 >> 综合 >> libxml2 如何进行字符串处理
  详细解决方案

libxml2 如何进行字符串处理

热度:7   发布时间:2024-01-04 08:33:32.0

libxml2

xmlReadMemory

xmlParseMemory

 

都是处理xml文件的,就没直接处理xml字符串的函数

 

1.     xmlParseMemory,字符串转为XML文档

2.     xmlDocGetRootElement,获取XML文档根节点

3.     xmlStrcmp,比较XML字符串,与strcmp差不多

4.     curr = curr->xmlChildrenNode,XML节点指针指向第一个子节点

5.     curr = curr->next,XML节点指针指向下一个兄弟节点

6.     xmlNodeGetContent,获取XML节点的内容

7.     xmlFreeDoc,释放节点,与free差不多

 

#include <iconv.h>  
#include <libxml/parser.h>  
#include <libxml/xmlmemory.h>  
#include "soapH.h"  
#include "ExchangeRateWebServiceSoap12.nsmap"  
#define FIELD_LEN 16  
int conv_charset(const char *dest, const char *src, char *input, size_t ilen, char *output, size_t olen) {  
iconv_t conv = iconv_open(dest, src);  
if ( conv == (iconv_t) -1 )  
return -1;  
memset(output, 0, olen);  
if ( iconv(conv, &input, &ilen, &output, &olen) )  
return -1;  
iconv_close(conv);  
return 0;  
}  
int main(int argc, char **argv) {  
if ( argc != 2 && argc != 3 ) {  
printf("Usage: %s type [end_point]\n", argv[0]);  
printf("\ttype = A : all rate\n");  
printf("\ttype = B : basic rate\n");  
printf("\ttype = C : cross rate\n");  
exit(-1);  
}  
struct soap soap;  
soap_init(&soap);  
// don't set is OK  
//soap_set_mode(&soap, SOAP_C_UTFSTRING);  
struct _ns1__getExchangeRate request;  
struct _ns1__getExchangeRateResponse response;  
request.theType = argv[1];  
char *endpoint = NULL;  
if ( argc == 3 )  
endpoint = argv[2];  
if ( soap_call___ns3__getExchangeRate(&soap, endpoint, NULL, &request, &response) == SOAP_OK ) {  
int len = strlen(response.getExchangeRateResult->__any);  
xmlDocPtr pdoc = xmlParseMemory(response.getExchangeRateResult->__any, len);  
xmlNodePtr root = xmlDocGetRootElement(pdoc);  
xmlNodePtr curr = root;  
while ( xmlStrcmp(curr->name, (const xmlChar *) "getExchangeRate") )  
curr = curr->xmlChildrenNode;  
for ( curr = curr->xmlChildrenNode; curr; curr = curr->next ) {  
xmlNodePtr data;  
for ( data = curr->xmlChildrenNode; data; data = data->next ) {  
char ifield[FIELD_LEN];  
char ofield[FIELD_LEN];  
strcpy(ifield, xmlNodeGetContent(data));  
if ( conv_charset("GBK", "UTF-8", ifield, strlen(ifield), ofield, FIELD_LEN) )  
printf("%s\t%s\n", data->name, ifield);  
else  
printf("%s\t%s\n", data->name, ofield);  
}  
printf("\n");  
}  
xmlFreeDoc(pdoc);  
}  
else {  
soap_print_fault(&soap, stderr);  
}  
soap_destroy(&soap);  
soap_end(&soap);  
soap_done(&soap);  
return 0;  
}  
  gcc -O2 -o exchange exchange.c soapC.c soapClient.c ../../stdsoap2.c -I../.. -I/usr/include/libxml2 -L../.. -lgsoap -lxml2