top of page

SAP ABAP Create XML Document

Creating an XML document in SAP S/4HANA ABAP involves using the XML transformation capabilities provided by the CL_SXML_STRING_SERIALIZER class to convert ABAP data into XML format. Here's a simple example of ABAP code to create an XML document:




REPORT z_create_xml_document.

DATA: lt_xml_data TYPE TABLE OF ty_xml_data,
      lv_xml_string TYPE string.

* Define a simple ABAP structure to hold data
DATA: BEGIN OF ty_xml_data OCCURS 0,
        field1 TYPE string,
        field2 TYPE i,
      END OF ty_xml_data.

* Fill the data structure with sample data
ty_xml_data-field1 = 'Item 1'.
ty_xml_data-field2 = 42.
APPEND ty_xml_data TO lt_xml_data.

ty_xml_data-field1 = 'Item 2'.
ty_xml_data-field2 = 99.
APPEND ty_xml_data TO lt_xml_data.

* Create an XML document from the data
DATA(lo_serializer) = NEW cl_sxml_string_serializer( ).

* Start building the XML structure
DATA(lo_document) = NEW cl_sxml_document( ).
DATA(lo_root_element) = lo_document->create_root_element(
  name = 'RootElement' ).

LOOP AT lt_xml_data INTO ty_xml_data.
 DATA(lo_item_element) = lo_root_element->create_element(
    name = 'Item' ).

 lo_item_element->create_text_node(
    name  = 'Field1'
    value = ty_xml_data-field1 ).

 lo_item_element->create_text_node(
    name  = 'Field2'
    value = ty_xml_data-field2 ).

ENDLOOP.

* Serialize the XML document to a string
lo_serializer->serialize(
  EXPORTING
    document        = lo_document
  IMPORTING
    string          = lv_xml_string
).

* Output the XML string
WRITE: / 'Generated XML Document:',
       / lv_xml_string.

In this code:


We define an internal table lt_xml_data to hold the data that we want to convert into an XML document.


We create a sample data structure ty_xml_data to represent each item in the XML document.


Inside the loop, we create XML elements and text nodes using the cl_sxml_document and cl_sxml_string_serializer classes.


The serialize method is used to convert the XML document into an XML string.


Finally, we output the generated XML string.


Make sure to adapt this code to your specific use case and data structure as needed. This is a basic example, and you can customize it to fit your requirements.





6 views0 comments
Post: Blog2_Post
bottom of page