Read an empty XML TEXT element

Verified
Added by iNTERFACEWARE

Demonstrates the best way to read an empty XML TEXT element, by using the text(' ') function from the xml.lua module

Source Code
require 'xml'

function main(Data)
   -- Parse the XML message
   local XML = xml.parse(Data)
   
   -- ORIGINAL CODE: Will cause errors with empty TEXT elements
   
   --local FirstName = XML.patients.patient["first-name"][1]:nodeValue()
   
   --local LastName = XML.patients.patient["last-name"][1]:nodeValue()
   
   --local SSN = XML.patients.patient["social-security-no"][1]:nodeValue()
   
   
   -- RECOMMENDED BEST PRACTICE: Use the text() funcion from the xml module
   
   -- FINAL CODE: Does not cause errors with empty TEXT elements
   
   local FirstName = XML.patients.patient["first-name"]:text():nodeValue()
   
   local LastName = XML.patients.patient["last-name"]:text():nodeValue()
   
   local SSN = XML.patients.patient["social-security-no"]:text():nodeValue()
   
end
Description
Demonstrates the best way to read an empty XML TEXT element, by using the text(' ') function from the xml.lua module
Usage Details

This code addresses an error that occurs when reading an empty XML TEXT element. The issue is a simple one: If you have an XML element with an empty string then the node:nodeValue() function raises an “Index N is out of bounds.” error, when the desired behaviour is to return an empty TEXT node.

We show you our recommended Best Practice solution, which uses the node:text() function, from XML techniques in the Protocols repository.

How to use the code:

  • Use a Filter or To Translator script
    • Add the code
    • Load the sample messages from SampleData.txt
      Note: You will need to split the six XML messages manually, as they are loaded as a single “message” when you import the the file into sample data
  • Alternatively you can also load the attached project which already contains the separated XML sample messages
  • Inspect the code and annotations to see how it works

Note: This code is explained in detail in the Reading an empty XML TEXT element from a node tree tutorial.