Concurrently read and write XML documents
- Last Updated: October 17, 2024
- 2 minute read
- OpenEdge
- Version 13.0
- Documentation
One common use case for the ABL SAX objects is to read a source XML document element by element, transform the elements, and output the updated elements to a new XML document. During this process, you might want to:
- Decide if the element should be included or excluded in the output
- Alter the attributes of the element
- Alter the content of the element
- Add new elements
- Rearrange elements
In this example, a simple XML document that represents address data is read in and transformed to create a new XML address list. You can read the comments embedded in the code to see examples of the kinds of changes that are possible. The example is provided as a single procedure which serves as both the SAX driver and the SAX handler (includes internal callback procedures).
The program transforms the source XML document in a single parse. This technique forces custom processing logic down into the callback procedures. This can quickly lead to added complexity as you mingle your transformation logic with the logic of the parser life cycle. In reality, you will likely use a progressive scan parse for anything more than simple adjustments to source XML. In this scenario, you would use the SAX-reader to feed your driver procedure the next piece of XML data, use the logic in your driver procedure to process the data, and output the desired XML data with the SAX writer object.
The following is a snippet of the source XML document sampledata2.xml.
sampledata2.xml
|
sax-readwrite.p
This is the sample code:
|
sax-readwrite.xml
The following partial sax-readwrite.xml output file shows key changes in bold:
|
Note that the SAX-writer object Start-Element( ) method
takes a SAX-attributes object as an optional parameter. In this
variation of the last example, all the transformation logic is stripped
out and a SAX-attributes object is created and populated with attributes
at the procedure's top (global) scope. The calls to the SAX-writer
object in the callback procedure ignore the SAX-attributes object
created by the parser for SAX-reader and only pass the global SAX-attributes
object to the SAX-writer if the current element is address.
The end result is that all attribute data in the source XML is lost
and only the attribute data created by the procedure is output to
the new XML document. Note the changes shown in bold:
sax-readwrite2.p
|
sax-readwrite2.xml
The following partial output XML document is the result:
|