BudiBadu Logo
Samplebadu

COBOL by Example: XML Generation

COBOL 2002

Converting COBOL data structures to XML with XML GENERATE statement, serializing group items automatically for web services, mapping field names to XML element tags, controlling output format with COUNT clause and WITH ENCODING, and handling buffer overflow with ON EXCEPTION error management.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. XML-GEN.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  CUSTOMER.
           05 ID-NUM   PIC 9(5) VALUE 12345.
           05 NAME     PIC X(10) VALUE "Alice".
       01  XML-OUT     PIC X(100).
       01  XML-CNT     PIC 999.
       
       PROCEDURE DIVISION.
           XML GENERATE XML-OUT FROM CUSTOMER
               COUNT IN XML-CNT
               ON EXCEPTION DISPLAY "XML Error"
               NOT ON EXCEPTION DISPLAY XML-OUT(1:XML-CNT)
           END-XML.
           STOP RUN.

Explanation

The XML GENERATE statement automatically serializes a COBOL group item into an XML document. This is incredibly useful for web services and data exchange, allowing legacy applications to participate in modern Service-Oriented Architectures (SOA).

The generated XML element names match the COBOL field names (e.g., <ID-NUM>12345</ID-NUM>). You can control the output format with various clauses, such as WITH ENCODING, WITH DECLARATION, or NAME OF to map COBOL names to different XML tags.

Exception handling is built-in via the ON EXCEPTION clause. This catches issues like buffer overflow (if the output string is too small) or data conversion errors, ensuring the program doesn't crash unexpectedly.

Code Breakdown

13
XML GENERATE XML-OUT. The command to start serialization. The result is stored in the XML-OUT variable.
13
FROM CUSTOMER. Specifies the source data structure. The entire hierarchy of CUSTOMER is converted to XML.
14
COUNT IN XML-CNT. Stores the actual number of characters generated. This is vital because XML-OUT is fixed-width and may contain trailing spaces.
15
ON EXCEPTION. Executes if an error occurs during generation (e.g., XML-OUT is too small).
16
NOT ON EXCEPTION. Executes if the generation was successful.
16
DISPLAY XML-OUT(1:XML-CNT). Uses reference modification to print only the valid XML characters, ignoring trailing garbage.