The XML Techniques component can be used to demonstrate strategies for parsing and generating XML documents in IguanaX using the XML LibraryWhen working with XML in the Translator, you can leverage the XML APIs and the XML Library to ingest, generate and process XML efficiently. It is highly recommended to import the XML library to extend capability and ease working with XML documents. Let’s break down these strategies one by one:
Generating XML:
To build an XML document, use a hardcoded template you can parse and build on. For example:
Code Block |
---|
local SampleXML = [[
<message>
</message>
]] |
Expand |
---|
|
There are two methods to adding elements to an existing XML document. With node.append() by providing what you want to create and a name.
Code Block |
---|
X.message:append(xml.ELEMENT,'observation_info') |
With the XML Library’s node.addElement() , by providing an element name.
Code Block |
---|
X.message:addElement("extra_info") |
You should see two new elements added to the XML document in the annotations. |
Expand |
---|
title | 2) Add and set an attribute |
---|
|
When adding and setting an attribute, you can use the XML library’s node.setAttr() to create and set an attribute in one line: Code Block |
---|
X.message.extra_info:setAttr("message_id", iguana.messageId()) |
instead of… Code Block |
---|
X.message.observation_info:append(xml.ATTRIBUTE,'id') -- add attribute
X.message.observation_info.id:setInner('123') -- set value |
|
Expand |
---|
title | 3) Add and set text elements |
---|
|
Use node.setText() to create and set text elements. Code Block |
---|
X.message.extra_info:setText("This is some extra text") |
|
Expand |
---|
title | 4) Add and set CDATA elements |
---|
|
To add and set CDATA you must use node.append() to specify you are creating a CDATA element and the content to set. Code Block |
---|
X.message.observation_info:append(xml.CDATA,'Because CDATA is not parsed it allows & and <>') |
|
Expand |
---|
title | 5) Add an element in a specific location in the xml |
---|
|
You can also add an element in s specific location in the XML document using node.insert() , specifying the location, an element node type and the content to set. Code Block |
---|
X.message:insert(1, xml.ELEMENT, 'first') |
|
...
title | 6) Serialize the xml node tree once ready to push downstream |
---|
Finally, once your XML document is ready, in order to queue it for a downstream component, write it to a file or send it in an HTTP request, it must be serialized as a string!
...
Refer to the XML Techniques component for further demonstration of strategies for parsing and generating XML documents.