3

I want to check if attribute in XML tag is present or not.

here is the sample xml tag: <value @code="">

i Want to check following conditions..

  1. if tag is present.
  2. if @code is present.
  3. if @code is null.

currently I am checking condition as below:

if(msg['value'])
{
  hasValue='true';
  
  if(msg['value']['@code'])
  {
      hasCode='true';
  }else
  {
    hasCode='false';
  }
  
}

but this condition returns hasValue flag always true. Even if @code is missing/undefined.

Is there a way to check if @code is undefined/missing?

AHP
  • 51
  • 1
  • 7

2 Answers2

2

hasOwnProperty is typically not used for xml (for people following the javascript tag, mirth embeds the Mozilla Rhino javascript engine, which uses the deprecated e4x standard for handling xml.) hasOwnProperty does not behave as expected when there are multiple child elements named value. From the naming convention, I'm assuming it is possible to have multiple values with different codes.

This will create an array for hasCode that holds a boolean for each occurrence of a child element named value.

var hasCode = [];
var hasValue = msg.value.length() > 0;
for each (var value in msg.value) {
    // Use this to make sure the attribute named code exists
    // hasCode.push(value['@code'].length() > 0);

    // Use this to make sure the attribute named code exists and does not contain an empty string
    // The toString will return an empty string even if the attribute does not exist
    hasCode.push(value['@code'].toString().length > 0);
}

(while length is a property on strings, it is a method on xml objects, so the parentheses are correct.)

agermano
  • 1,679
  • 6
  • 16
0

You can use hasOwnProperty() to check for the existence of an element or attribute, and you can use .toString() to check whether the attribute value is empty or not.

if(msg.hasOwnProperty('value')) {
  hasValue='true';

  if(msg.value.hasOwnProperty('@code') && msg.value['@code'].toString()) {
    hasCode='true';
  } else {
    hasCode='false';
  }
}
Daniel Elkington
  • 2,560
  • 6
  • 22
  • 35