Monday, 07 February 2011
Accessing EDI data with Java can be even easier with the new EDIStAX module that supports the Streaming API for XML (StAX). A traditional SAX-based approach puts the parser in control and the parser calls a handler to react to XML elements. With StAX, the application is in control and calls the parser when it needs to get another XML event.

Here is a tiny Java program that illustrates this approach. It simply iterates through the elements of EDI input and prints each segment type noted within an EDI transaction. Notice that the program uses only the XML streaming API included with Java; the "XML" it is processing is actually EDI parsed by EDIReader, masquerading as an XML parser.

package com.berryworks.edireader.stax.demo;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.*;

public class Demo {
   private void run(Reader reader) throws XMLStreamException {

     XMLEventReader eventReader =

     while (eventReader.hasNext()) {

       XMLEvent xmlEvent = eventReader.nextEvent();

       if (xmlEvent.isStartElement()) {

         StartElement startElement = (StartElement) xmlEvent;
         String name = startElement.getName().getLocalPart();

         if ("transaction".equals(name)) {
           System.out.println("Transaction set");

         } else if ("segment".equals(name)) {
             Attribute idAttribute =
               startElement.getAttributeByName(new QName("Id"));
             System.out.println( idAttribute.getValue() + " segment");

     public static void main(String[] args) {
       if (args.length < 1) {
         System.err.println("Specify EDI input file as a command line argument");
       try {
         new Demo().run(new FileReader(args[0]));
       } catch (Exception e) {
Last Updated ( Monday, 27 July 2015 )