Question
· Oct 24, 2016

In the Ensemble DTL, how do you test if an XML element exists in the source document

Hi,

 

I have an Ensemble DTL which is suppose to translate the inbound XML document to an outbound XML document.

I need to test if a particular XML element exists, to perform some translation.

In the DTL I have the following,

<if condition='source.{element1.element2.element3}'>

<true>

    // do something

</true>

</if>

How do you use if statement to test the source XML document to see if a particular element exists in the source doucment.

 

Thanks,

Discussion (2)0
Log in or sign up to continue

If you just want to know whether there is a value or not in element1.element2.element3, compare it to "".  The 'not equal' ('=) operator in Cache contains an apostrophe, so it must be escaped in the XML. (if a '= b write "a is not equal to b")

<if condition='source.{element1.element2.element3}&apos;=""'>

This will return True if element1.element2.element3 has a value, or it will return False if either element1.element2.element3 does not exist or if element1.element2.element3 exists but contains no value, like this:

<element3></element3>

If you need to differentiate between these two cases, things get more difficult.  There is no method in XML VDoc that can tell you whether an element exists or not.  In general with XML, the existence of an element shouldn't be used as a logical boolean value.  Instead you should use a boolean datatype in your XML schema.

If you must check whether element3 exists or not, you could do it like this:

say your XML document looks like this:

<element1><element2><element3>sometext</element3></element2></element1>

If you were to get the value of element2 with an assign action like this:

<assign value='element1.element2' property='e2' action='set' />

then after that line, the variable e2 will hold the value "<element3>sometext</element3>" so to check for the existence of element3, you could search e2 for the text "<element3>" with the ..Contains function:

<if condition='..Contains(e2,"&lt;element3&gt;")' >

If your element3 might be self-closed (like this: <element3 />) then you'll need to account for that possibility as well.

I just thought of another method.  Getting the count should work for checking for existence as well.  If using DOM-style paths, then get the count with [*] and if using VDoc style paths, then get the count with (*).  Using the VDoc path example from above:

<if condition='source.{element1.element2.element3(*)}&gt;0'>

This will return True if there are any element3's inside the element2.  It will return False if there are not.