
Introduction
HCI allows the usage of scripting languages in Integration Flows which can be used to enhance the functionality of the integration flow. Groovy scripts or Javascript can be implemented as a Message Transformer block or as a User Defined Function for Message Mappings.
Groovy is a dynamic language with native functionality to handle XML processing easily. Compared to Java, implementing logic for XML processing is really simple in Groovy, it is not as complex as DOM and have a low memory footprint as it is based on SAX.
In this blog, I will share some simple examples of how XML can be parsed easily in Groovy.
Examples
The examples below will all use the following input XML payload.
Input Payload |
---|
|
Scenario 1 - Read-only access to input XML
For read-only access to the input XML, it is recommended to use groovy.util.XmlSlurper. XmlSlurper contains a parseText() method which returns a GPathResult for the root element. Using this GPathResult object, accessing the content of the document can easily be done in an XPath-like manner. As shown in the logic below, the text contents of /Records/Line/Field1 and /Records/Line/Field4 are accessed using dot notation without any further declarations or DOM-like complex logic.
Logic |
---|
|
Below is the console output for the above example verifying the successful extraction of the two field contents.
Scenario 2 - Change content of a field in input XML
If the input XML needs to be updated/changed during parsing, it is recommended to use groovy.util.XmlParser instead. Similar to above, it contains a parseText() method but returns a Node for the root element. Similarly, using GPath dot notation, content of the field can be directly modified as shown below for /Records/Line/Field1.
Logic |
---|
|
Below is the console output verifying the successful modification of the field.
Scenario 3 - Add a new field in input XML
Similar to scenario 2, XmlParser is used to parse the input XML. In order to add a new field, the appendNode() method is used to add a new field and initialize the text content in it.
Logic |
---|
|
Below is the console output verifying the successful addition of a new field in the XML payload.
Conclusion
As demonstrated from the examples above, parsing of XML content is significantly simpler to implement in Groovy with the use of XmlParser and XmlSlurper.
Reference
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
11 | |
7 | |
5 | |
4 | |
4 | |
4 | |
4 | |
3 | |
3 | |
3 |