KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: How to Find a Specific Element in an XML Document
PRODUCT: 4D | VERSION: 2003 | PLATFORM: Mac & Win
Published On: August 26, 2004
Your current browser may not allow you to download the asset. We recommend Mozilla Firefox or Google Chrome.
Log In

In parsing XML documents, a time may arise where you may need the value or attributes of a specific element. It is possible, as will be shown, to find a specific element in an XML document using 4D 2003 XML commands.

Suppose that the method is named FindXMLElement:

C_STRING(16;$1;$root;$0;$foundNode;$node)
C_TEXT($2;$findName;$nodeName;$foundName)
$root:=$1
$findName:=$2
$node:=""
$foundNode:=""

If ($root#"")
  $node:=DOM Get First XML element($root;$nodeName)

  While (($nodeName#$findName) & (OK=1))
    $nodeName:=""
    $foundNode:=FindXMLElement ($node;$findName)
    If(OK=0)
      $node:=DOM Get Next XML element($node;$nodeName)
    Else
      $nodeName:=$findName
      $node:=$foundNode
    End if
  End while
End if

$0:=$node

XML documents are organized as a "tree", so a recursive call makes parsing cleaner. However, it may require more stack space than a regular call, so be sure to increase your stack size from the preferences in 4D.

What the above method does is find the first occurrence of an element matching a name and return a reference to it, otherwise, it returns the empty string ("").

Now take the following XML document, called MyXML.xml, for example:

<a>
 <d>
  </d>
  <b>
    <e>
      <f/>
      <c>my name is c</c>
 :   </e>
  </b>
</a>

Now, you can find an element using the method given above:

$root:=DOM Parse XML source("MyXML.xml")
$node:=FindXMLElement ($root;"c")
DOM GET XML ELEMENT VALUE($node;$value)

The value of $node contains a reference to the element "c" while $value contains its character data value.