Check if element exists in xml or not

Hi,
a requirement where to check if <VW>ER</VW> exists in xml or not.
sample xml 1:-

<?xml version="1.0" encoding="UTF-8"?>
<ORDER>
	<IDOC BEGIN="1">
		<KA1 SEGMENT="1">
			<VW>ZB</VW>
			<TN>6778</TN>
			<NR>708000</NR>
		</KA1>
		<KA1 SEGMENT="1">
			<VW>ER</VW>
			<TN>600729</TN>
			<NR>4018611</NR>
		</KA1>
	</IDOC>
</ORDER>

then I need flag = Y

sample xml 2:-

<?xml version="1.0" encoding="UTF-8"?>
<ORDER>
	<IDOC BEGIN="1">
		<KA1 SEGMENT="1">
			<VW>ZB</VW>
			<TN>6778</TN>
			<NR>708000</NR>
		</KA1>
		<KA1 SEGMENT="1">
			<VW>RE</VW>
			<TN>600729</TN>
			<NR>4018611</NR>
		</KA1>
	</IDOC>
</ORDER>

then I need flag = N

Hi @Sahil,

Try this expression. In Mapper also need to check Pass Though.

sl.ensureArray($ORDER.IDOC.KA1).find(f => f.get("VW") == "ER") != null ? "Y" :  "N"

Regards,
Viktor

1 Like

@viktor_n , I want to read more into sl.ensureArray, could you please share some links.

Here is a link of the documentation.
https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1439396/SL+Functions+and+Properties#SLFunctionsandProperties-sl.ensureArray

Here in the expression I am using sl.ensureArray() to transform KA1 into an array, since it is an object.

When you work with xml data, if there are more same elements as it is KA1 in this situation, XML Parser will see it as Array, but if there’s only one element with the name KA1, the parser will accept it as object.

.find() function works only with Arrays so in order for the expression not to fail we need to make sure that the element we are trying to map is not an array.

Hope this will help you understand ensureArray a little bit more. If it need anything else, I will be happy to help :slight_smile: