KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Finding an XML element's attribute value by name
PRODUCT: 4D | VERSION: 2003 | PLATFORM: Mac & Win
Published On: May 13, 2004

When parsing the DOM of an XML instance document, you may come across a time when you need to retrieve an attribute for a set of elements. The problem is that the attributes of those elements are not required, so some have them and some do not. For example:

<myXML>
 <element attribute="value">Hello</element>
 <element>World</element>
</myXML>

If you use the command GET ATTRIBUTE BY NAME and the attribute does not exist, an error is returned (which can be quite annoying in a loop). Now instead of trapping the error, you can just create a wrapper method that uses GET ATTRIBUTE BY INDEX instead.

The following method attempts to find an attribute of a certain name and returns its value if it found it or the empty string if it did not.

  ` ----------------------------------------------------
  ` Method: Helper_GetElementAttributeValue
  ` Description
  `
  `
  ` Parameters
  ` $1 - the element reference node of the element for which we want to find the attribute
  ` $2 - the name of the attribute we are looking for
  ` return - the value of the attribute or null string if not found
  ` ----------------------------------------------------
C_TEXT($1;$2)

C_TEXT($elemRef)
$elemRef:=$1

C_TEXT($searchName)
$searchName:=$2

C_LONGINT($i;$attribCount)
C_TEXT($attribName;$attribValue)
$attribCount:=Count XML attributes($elemRef)

 ` look for the attribute until we find something
For ($i;1;$attribCount)
 GET XML ATTRIBUTE BY INDEX($elemRef;$i;$attribName;$attribValue)
 If ($attribName=$searchName)
   ` when we find something we short-circuit to the end
   $i:=$attribCount
 End if
End for

 ` return null or the attribute's value
$0:=$attribValue