将包含XML文本的base64解码为字符串变量



我无法解码以基本64格式提供的XML,字符串变量(lv_string)显示不可读的东西。

示例:

在的

这是代码:

Data: lt_content    Type standard table of x255,
      lv_xstring    Type xstring,
      lv_string     Type string,
      encod         Type Abap_encoding Value 4110.
Select Single xml_dte into @Data(xml_b64)
 From zmmvf_edocdet 
  Where numinterno = '0000000012'.
  IF Sy-subrc Eq 0.
    Call function 'SCMS_BASE64_DECODE_STR'
     Exporting
      Input         = xml_b64
     Importing
      Output        = lv_xstring
     Exceptions
      Failed        = 1
      Others        = 2.
    If Sy-subrc Eq 0.
      Data(lv_len) = xstrlen( lv_xstring ).
      Call function 'SCMS_XSTRING_TO_BINARY'
       Exporting
        buffer        = lv_xstring
       Importing
        output_length = lv_len
       Tables
        binary_tab    = lt_content[].
      Call function 'SCMS_BINARY_TO_STRING'
       Exporting
        input_length = lv_len
*        encoding     = encod
       Importing
        text_buffer  = lv_string
       Tables
        binary_tab   = lt_content[]
       Exceptions
        failed       = 1
        Others       = 2.
    ENDIF.
  ENDIF.

我过去也有这个问题。您可以使用以下

data:
  lv_base64 type string,
  lv_xstring type xstring,
  lv_output type string.
* example base64 string
lv_base64 = 'PGh0bWw+PGhlYWQ+PHRpdGxlPlRpdGxlPC90aXRsZT48L2hlYWQ+PGJvZHk+PHA+SGVsbG8gV29ybGQ8L3A+PC9ib2R5PjwvaHRtbD4='.
* convert base64 to binary (xstring)
call function 'SCMS_BASE64_DECODE_STR'
    exporting
      input  = lv_base64
    importing
      output = lv_xstring
    exceptions
      failed = 1
      others = 2.
* use codepage conversion to convert xstring to string (UTF-8)
* catch possible conversion errors
  try.
      lv_output = cl_abap_codepage=>convert_from( source = lv_xstring ).
    catch cx_parameter_invalid_range .
    catch cx_sy_codepage_converter_init .
    catch cx_sy_conversion_codepage .
    catch cx_parameter_invalid_type .
  endtry.
  write lv_output.

结果是以下输出

<html><head><title>Title</title></head><body><p>Hello World</p></body></html>

您可以使用其他参数控制转换,例如:

如果您更喜欢有不同的codepage

如果您想用特殊的char

替换不可见字符

如果您想忽略转换错误

lv_output = cl_abap_codepage=>convert_from(
    source      = lv_xstring
    codepage    = <your favourite codepage here>
    replacement = <conversion char for not convertible chars>
    ignore_cerr = <pass 'X' to ignore conversion errors>
).

一个简短的解决方案,如果我们假设base64字符串在 UTF-8编码中包含XML,则使用CL_HTTP_UTILITY类的方法DECODE_BASE64

lv_string = cl_http_utility=>if_http_utility~decode_base64( xml_b64 ).

最小,完整和可验证的示例:

(请允许我重复使用@manuel_b的好例子)

DATA(xml_b64) = `PGh0bWw+PGhlYWQ+PHRpdGxlPlRpdGxlPC90aXRsZT48L2hlYWQ+`
             && `PGJvZHk+PHA+SGVsbG8gV29ybGQ8L3A+PC9ib2R5PjwvaHRtbD4=`.
DATA(lv_string) = cl_http_utility=>if_http_utility~decode_base64( xml_b64 ).
ASSERT lv_string = `<html><head><title>Title</title></head><body><p>Hello World</p></body></html>`.

相关内容

  • 没有找到相关文章

最新更新