LR对XML格式的字符串的提取方法,即获得子串的方法
Char *szResponse 的内容如下
<?xml version="1.0" encoding="GBK"?><CMBSDKPGK><INFO><DATTYP>2</DATTYP><ERRMSG>4262: 出现错误</ERRMSG><FUNNAM>AgentRequest</FUNNAM><LGNNAM>XNCS1</LGNNAM><RETCOD>-9</RETCOD></INFO></CMBSDKPGK>
需要提取<RETCOD>字段 及<ERRMSG>所包含的内容。其中,RETCOD为0,或者负数,0代表正常,负数则对应相应的错误。当RETCOD不为0时,<ERRMSG>则给出具体的错误信息。
由于LR所支持的ANSIC中并没有substr函数,所以不能直接对szResponse 进行子串操作。
以下是几种处理方法:
1 查阅LR的帮助中关于C函数的内容。利用以下两函数可实现
Returns the first occurrence of one string in another.
char *strstr ( const char *string1, const char *string2 );
string1 The string that is searched.
string2 The string that is searched for in the first string.
strstr returns the first occurrence of one string in another.
Copies the first n characters of one string to another.
char *strncpy ( char *dest, const char *source, size_t n );
dest The destination string to which n characters are copied.
source The source string from which n characters are copied.
n The number of characters copied.
strncpy copies the first n characters of one string to another.
首先利用strstr 分别查找<RETCOD>与</RETCOD>在szResponse 中的地址,从而计算出它们所包含内容的首地址与长度;然后利用strncpy 获得所字段内容。
iFirstRetCode = strstr(szResponse,"<RETCOD>");
iSecondRetCode = strstr(szResponse,"</RETCOD>");
strncpy(szRetCode , (char*)(iFirstRetCode + iSecondRetCode), iSecondRetCode -iFirstRetCode - strlen("<RETCOD>"));
其中,szRetCode 为所求。
2 与第一种方法类似,前面依然采用strstr , 但后面则利用memcpy
iFirstRetCode = strstr(szResponse,"<RETCOD>");
iSecondRetCode = strstr(szResponse,"</RETCOD>");
strncpy(szRetCode,(char *)(iFirstRetCode + strlen("<RETCOD>")), iSecondRetCode -iFirstRetCode - strlen("<RETCOD>") )
3 每三种方法则不利用C提供的字符串函数,而是利用LR关于XML处理函数lr_xml_get_values
lr_save_string(szResponse , "XML_Input_Param"); // Save szResponse as
lr_xml_get_values("XML={XML_Input_Param}",
"ValueParam=OutputParam",
"Query=/CMBSDKPGK/RETCOD", //这里指明所求内容所在XML的结构层次
LAST);
lr_output_message(lr_eval_string("Query result = {OutputParam}"));
个人推荐第三种方法