KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Handling errors with DOM GET XML ELEMENT
PRODUCT: 4D | VERSION: 12.2 | PLATFORM: Mac & Win
Published On: May 27, 2011

When you run the command DOM Get XML element it is assumed that you know the specified element exists. The command is not a "find" like Find in array is, where you are trying to find a value and it may or may not exist. Because of that, if the specified element does not exist under the root element passed to DOM Get XML element then an error is generated.

The following code displays the error message "The name of the element is unkown. The XML command cannot be executed" on line 4:

$Root:="MyNameSpace:MyRoot"
$Namespace:="https://www.4D.com/tech/namespace"
$vElemRef:=DOM Create XML Ref($Root;$Namespace)
$newref:=DOM Get XML element($vElemRef;"hi";1;$val) //Error here


That said you can use the DOM Get XML element command like a "find" so long as you implement error handling. The idea is to catch the error so the user doesn't see it, and if the XML element is missing, then report that. By replacing the call to DOM Get XML element with a utility method as shown below this can be avoided. Here is an example utility method:

  //Method name: UTIL_DOM_Find_XML_element
C_TEXT($1;$vElemRef;$2;$vElem;$0;$vReturnRef;$vMethCurrent)
C_POINTER($4;$val)
C_LONGINT($3;$index)
If (Count parameters>3)
  $vElemRef:=$1
  $vElem:=$2
  $index:=$3
  $val:=$4
  $vMethCurrent:=Method called on error
  ON ERR CALL("blankmethod") //"blankmethod" is literally a blank project method
  $vReturnRef:=DOM Get XML element($vElemRef;$vElem;$index;$val->)
  ON ERR CALL($vMethCurrent)
  If (OK=1)
    $0:=$vReturnRef
  Else
    $0:="ERROR not found"
  End if
Else
  $0:="ERROR parameters"
End if


Here is an updated example calling the utility method:

$Root:="MyNameSpace:MyRoot"
$Namespace:="https://www.4D.com/tech/namespace"
$vElemRef:=DOM Create XML Ref($Root;$Namespace)
$newref:=UTIL_DOM_Find_XML_element($vElemRef;"hi";1;->$val) //No error