Skip to content

Reading EDI Data (Simple)

Michael Edgar edited this page Jul 31, 2020 · 6 revisions

This article assumes the reader has basic knowledge of EDI structures and terminology

Reading EDI

Reading EDI data using StAEDI allows you to receive a stream of events representing the data in an EDI document. Suppose we have a very simple example of an X12 interchange acknowledgement.

ISA*00*          *00*          *ZZ*Receiver       *ZZ*Sender         *200301*1430*^*00501*000000001*0*P*:~
TA1*000000050*200229*1200*A*000~
IEA*1*000000001~

To retrieve the acknowledgement status from the file (elements TA104 and TA105), a basic program using StAEDI could be as follows.

package com.example;

import java.io.FileInputStream;
import java.io.InputStream;

import io.xlate.edi.stream.EDIInputFactory;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamException;
import io.xlate.edi.stream.EDIStreamReader;

public class ReadInterchangeAcknowledgementTest {

    public boolean isAcknowledgementSuccess() throws Exception {
        EDIInputFactory factory = EDIInputFactory.newFactory();
        String ta104 = null;
        String ta105 = null;

        /* (1) Open the EDI file - any InputStream can be used. */
        try (InputStream stream = new FileInputStream("x12_interchange_ack.txt")) {
            /* (2) Create a new EDIStreamReader */
            EDIStreamReader reader = factory.createEDIStreamReader(stream);
            EDIStreamEvent event;
            String segment = null;

            /* (3) Loop over the reader's events */
            while (reader.hasNext()) {
                event = reader.next();

                if (event == EDIStreamEvent.START_SEGMENT) {
                    /* (4)
                     * Each time a segment is encountered, save the
                     * segment tag in a local variable */
                    segment = reader.getText();
                } else if (event == EDIStreamEvent.ELEMENT_DATA) {
                    if ("TA1".equals(segment)) {
                        /* (5)
                         * When reading element data, if the current
                         * segment is TA1 and the current element is
                         * in either position 4 or 5, save the element
                         * data in a local variable */
                        if (reader.getLocation().getElementPosition() == 4) {
                            ta104 = reader.getText();
                        } else if (reader.getLocation().getElementPosition() == 5) {
                            ta105 = reader.getText();
                        }
                    }
                }
            }
        }

        return "A".equals(ta104) && "000".equals(ta105);
    }
}

In this example, the code is focused on retrieving only two elements from the EDI data (TA104 and TA105) and ultimately testing whether they contain specific values.