Skip to main content

Working with XML in RPGLE : XML-SAX

Working with XML in RPGLE : XML-SAX

Working with XML has never been easier before IBM's introduction of XML-INTO and XML-SAX compatibility to RPGLE.

My earlier post did contain detailed info about basics on XML with RPGLE and compatibility of XML-INTO with RPGLE along with its own advantages and disadvantages. If you haven't gone through them yet, Click on those links to have quick look.

XML-SAX:

Even though XML-INTO provides the greatest comfort to programmers by directly bringing the data to Respective variable/data structure. But, this doesn't help programmers when the XML elements/data has been inconsistent.

XML-SAX is the best way of handling such XMLs. This will read the XML character by character and calls Handling Procedure when the even gets triggered.

Syntax:

Xml-Sax(e) %Handler(XMLHandler_Procedure : CommsArea_DataStructure ) %XML(wXmlString: 'doc=string')

Below are some possible events that can occur while parsing XML. 

This has been split by the phase those events can occur along with its description to understand better.

Events discovered before the first XML element:

  • *XML_START_DOCUMENT - Indicates that parsing has begun
  • *XML_VERSION_INFO - The "version" value from the XML declaration
  • *XML_ENCODING_DECL - The "encoding" value from the XML declaration
  • *XML_STANDALONE_DECL - The "standalone" value from the XML declaration
  • *XML_DOCTYPE_DECL - The value of the Document Type Declaration

Events related to XML elements

  • *XML_START_ELEMENT- The name of the XML element that is starting
  • *XML_CHARS - The value of the XML element
  • *XML_PREDEF_REF - The value of a predefined reference
  • *XML_UCS2_REF - The value of a UCS-2 reference
  • *XML_UNKNOWN_REF - The name of an unknown entity reference
  • *XML_END_ELEMENT - The name of the XML element that is ending

Events related to XML attributes

  • *XML_ATTR_NAME - The name of the attribute
  • *XML_ATTR_CHARS - The value of the attribute
  • *XML_ATTR_PREDEF_REF - The value of a predefined reference
  • *XML_ATTR_UCS2_REF - The value of a UCS-2 reference
  • *XML_UNKNOWN_ATTR_REF - The name of an unknown entity reference
  • *XML_END_ATTR - Indicates the end of the attribute

Events related to XML processing instructions

  • *XML_PI_TARGET - The name of the target
  • *XML_PI_DATA - The value of the data

Events related to XML CDATA sections

  • *XML_START_CDATA - The beginning of the CDATA section
  • *XML_CHARS - The value of the CDATA section
  • *XML_END_CDATA - The end of the CDATA section

Other events

  • *XML_COMMENT - The value of the XML comment
  • *XML_EXCEPTION - Indicates that the parser discovered an error
  • *XML_END_DOCUMENT - Indicates that parsing has ended
Below example will show on how to use some of the basic events that usually occur. 

E.g.:

H DftActGrp(*No)                                                           
 // Standalone Variables Declaration                                       
D wSampleXml      S            512A                                        
D wXmlOptions     S            512A   Varying                              
D SaveElement     S             50A                                        
                                                                           
 // Data Structure for Communication Area                                  
D DsCommunicationArea...                                                   
D                 DS                                                       
D  AttrName                     20A   Varying                              
D  HaveAttr                       N                                        
D  AttrValue                    20A   Varying                              
                                                                           
D DsCommArea      DS                  LikeDs(DsCommunicationArea)          
                                                                           
 // Handling Procedure Prototype                                           
D pHandlingProcedure...                                                    
D                 PR            10I 0                                      
D  pCommArea                          LikeDs(DsCommunicationArea)          
D  pEvent                       10I 0 Value                                
D  pString                        *   Value                                
D  pStringLen                   20I 0 Value                                
D  pExceptionId                 10I 0 Value                                
 /Free                                                                     
                                                                           
   wSampleXml  = '<Order>'                                                 
               + '<Type>Weborder</Type>'                                   
               + '<Number>123456789</Number>'                              
               + '<Customer>Mr. John</Customer>'                           
               + '<Status>Despatched</Status>'                             
               + '</Order>' ;                                              
                                                                           
   wSampleXml  = %Xlate(x'3f' : x'40' : wSampleXml) ;                      
                                                                           
   wXmlOptions = 'doc=string ';                                            
                                                                           
   Xml-Sax(E) %Handler(pHandlingProcedure : DsCommArea)                    
              %Xml(wSampleXml : wXmlOptions) ;                             
   If %Error() ;                                                           
      Dsply 'Error Occured While Parsing XML. Please Review.' ;            
   EndIf ;                                                                 
                                                                           
   *InLr = *On ;                                                           
                                                                           
 /End-Free                                                                 
 // Handling Procedure for XML-SAX                                         
P pHandlingProcedure...                                                    
P                 B                                                        
D pHandlingProcedure...                                                    
D                 PI            10I 0                                      
D  pCommArea                          LikeDs(DsCommunicationArea)          
D  pEvent                       10I 0 Value                                
D  pString                        *   Value                                
D  pStringLen                   20I 0 Value                                
D  pExceptionId                 10I 0 Value                                
                                                                           
 // Work Variables Declaration                                             
D wReturnValue    S             10I 0 Inz(0)                               
D Value           S          65535A   Based(pString)                       
                                                                           
 /Free                                                                     
                                                                           
    Select ;                                                               
    When pEvent = *XML_START_DOCUMENT ;                                    
      pCommArea.HaveAttr = *Off ;                                          
      Dsply 'Initialize Local Variables. If any' ;                         
    When pEvent = *XML_START_ELEMENT ;                                     
      SaveElement = %Subst(Value:1:pStringLen);                            
      Dsply SaveElement ;                                                  
    When pEvent = *XML_CHARS ;                                             
      SaveElement = %Subst(Value:1:pStringLen);                            
      Dsply SaveElement ;                                                  
    When pEvent = *XML_END_ELEMENT ;                                       
      SaveElement = %Subst(Value:1:pStringLen);                            
      Dsply SaveElement ;                                                  
    When pEvent = *XML_ATTR_NAME ;                                         
      pCommArea.AttrName = %Subst(Value:1:pStringLen);                     
      Dsply pCommArea.AttrName ;                                           
    When pEvent = *XML_ATTR_CHARS ;                                        
      pCommArea.AttrValue = %Subst(Value:1:pStringLen);                    
      Dsply pCommArea.AttrValue ;                                          
    When pEvent = *XML_END_ATTR ;                                          
      pCommArea.AttrName = %Subst(Value:1:pStringLen);                     
      Dsply pCommArea.AttrName ;                                           
    When pEvent = *XML_END_DOCUMENT ;                                      
      wReturnValue = -1 ;                                                  
      Dsply 'No Further Parsing is Needed' ;                               
    EndSl ;                                                                
    Return wReturnValue ;                                                  
                                                                           
 /End-Free                                                                 
P pHandlingProcedure...                                                    
P                 E                                                    
In this example, we are storing XML data into Variable and using Option 'doc=string'. 

If the XML has been stored on IFS path. Same program can be considered as an example by just simple change.
  • Initialize the wSampleXml with IFS path.
D wSampleXml      S            512A   Inz('home/PReddy/SampleXml.xml')   
  • Remove the XML Population into wSampleXml variable.
  • Use 'doc=file' in XML options.
   wXmlOptions = 'doc=string ';        

You can try on by replacing 'Dsply' Statements with actual requirement.

Comments

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i