Sometimes it is convenient to print out the XML with simple WRITES as readable output
or save the XML as formatted file and not as a long string.
Below two examples for the XML pretty printer functionality.
First, very compact and elegant example which utilizes the standard transformation ID_INDENT . You can have a look at it through the transaction STRANS . See the following program:
REPORT zxml_pretty_print_2.
DATA:
lv_input_xml TYPE string VALUE '<?xml version="1.0" encoding="utf-16"?><xxx><item><bname>USR12345</bname><trdat>0000-00-00</trdat></item></xxx>',
lv_formated_xml TYPE string.
CALL TRANSFORMATION id_indent
SOURCE XML lv_input_xml
RESULT XML lv_formated_xml.
SPLIT lv_formated_xml AT cl_abap_char_utilities=>newline INTO TABLE DATA(lt_string).
LOOP AT lt_string INTO DATA(lv_string).
WRITE: / lv_string.
ENDLOOP.
it generates such output:
<?xml version="1.0" encoding="utf-16"?>
<xxx>
<item>
<bname>USR12345</bname>
<trdat>0000-00-00</trdat>
</item>
</xxx>
And here the other much longer coding, which generates the same output. It uses some standard functions instead of CALL TRANSFORMATION .
...
PERFORM xml_pretty_printer USING lv_input_xml
CHANGING lt_formated_xml.
FORM xml_pretty_printer USING pi_input_xml TYPE string
CHANGING pt_formated_xml TYPE string_table.
DATA:
lv_xstring TYPE xstring,
lr_document TYPE REF TO if_ixml_document,
lt_binary TYPE STANDARD TABLE OF x255,
lv_output_length TYPE i,
lv_formated_xml TYPE string.
CALL FUNCTION 'SCMS_STRING_TO_XSTRING'
EXPORTING
text = pi_input_xml
* MIMETYPE = ' '
* ENCODING = ' '
IMPORTING
buffer = lv_xstring
EXCEPTIONS
failed = 1
OTHERS = 2.
IF sy-subrc <> 0.
MESSAGE e676(bt) WITH 'SCMS_STRING_TO_XSTRING' sy-subrc.
ENDIF.
CALL FUNCTION 'SDIXML_XML_TO_DOM'
EXPORTING
xml = lv_xstring
* SIZE =
* IS_NORMALIZING = 'X'
IMPORTING
document = lr_document
EXCEPTIONS
invalid_input = 1
OTHERS = 2.
IF sy-subrc <> 0.
MESSAGE e676(bt) WITH 'SDIXML_XML_TO_DOM' sy-subrc.
ENDIF.
CALL FUNCTION 'SDIXML_DOM_TO_XML'
EXPORTING
document = lr_document
pretty_print = 'X'
IMPORTING
xml_as_string = lv_xstring
* SIZE =
* TABLES
* XML_AS_TABLE = lt_table
EXCEPTIONS
no_document = 1
OTHERS = 2.
IF sy-subrc <> 0.
MESSAGE e676(bt) WITH 'SDIXML_DOM_TO_XML' sy-subrc.
ENDIF.
CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
EXPORTING
buffer = lv_xstring
* APPEND_TO_TABLE = ' '
IMPORTING
output_length = lv_output_length
TABLES
binary_tab = lt_binary.
CALL FUNCTION 'SCMS_BINARY_TO_STRING'
EXPORTING
input_length = lv_output_length
* FIRST_LINE = 0
* LAST_LINE = 0
* MIMETYPE = ' '
* ENCODING =
IMPORTING
text_buffer = lv_formated_xml
* OUTPUT_LENGTH =
TABLES
binary_tab = lt_binary
EXCEPTIONS
failed = 1
OTHERS = 2.
IF sy-subrc <> 0.
MESSAGE e676(bt) WITH 'SCMS_BINARY_TO_STRING' sy-subrc.
ENDIF.
SPLIT lv_formated_xml AT cl_abap_char_utilities=>newline INTO TABLE pt_formated_xml.
ENDFORM.
See other related notes on my website: