Iterating over elements by using a .NETCompute node

Use the Where method to provide a sequential iteration over elements in the message tree.

About this task

You can use the resulting array in a foreach() statement to iterate over the children of an NBElement. The foreach() loop allows a developer to act on each NBElement in turn. The example below shows how this can be used to create a similar shape output message to the input message. Consider a simple XML input message:
<MessageEnvelope>
	<Element>1</Element>
	<Element>2</Element>
	<Element>3</Element>
</MessageEnvelope>
The following C# code in a .NETCompute node iterates over the elements:

        public override void Evaluate(NBMessageAssembly inputAssembly)
        {
            NBOutputTerminal outTerminal = OutputTerminal("out");

            NBMessage inputMessage = inputAssembly.Message;

            // Create a new empty message, ensuring it is disposed after use
            using (NBMessage outputMessage = new NBMessage())
            {
                NBMessageAssembly outAssembly = new NBMessageAssembly(inputAssembly, outputMessage);
                NBElement inputRoot = inputMessage.RootElement;
                NBElement outputRoot = outputMessage.RootElement;

                // Optionally copy message headers, remove if not needed
                CopyMessageHeaders(inputRoot, outputRoot);

                #region UserCode
                // Add user code in this region to create a new output message
                outputRoot.CreateLastChildUsingNewParser("XMLNSC");
                outputRoot["XMLNSC"].CreateLastChild("OutputMessageEnvelope");
                string notargetnamespace = "";
                NBElement env = inputRoot["XMLNSC"]["MessageEnvelope"];
                var elementlist = env.Where(t => t.Name == "Element");                
                foreach (NBElement element in elementlist)
                {
                    int currentvalue = (Int32)element;                   
                    NBElement outelement = outputRoot["XMLNSC"]["OutputMessageEnvelope"].CreateLastChild(notargetnamespace, "OutElement");
                    outelement.SetValue("After adding 1 to input value we get " + (currentvalue + 1).ToString());
                }
                #endregion UserCode

                // Change the following if not propagating message to the 'Out' terminal
                outTerminal.Propagate(outAssembly);
            }
        }
The output is an XML message:
<OutputMessageEnvelope>
	<OutElement>After adding 1 to input value we get value 2</OutElement>
	<OutElement>After adding 1 to input value we get value 3</OutElement>
	<OutElement>After adding 1 to input value we get value 4</OutElement>
</OutputMessageEnvelope>

For information about the .NET classes and methods that are supported in IBM® App Connect Enterprise, see the .NET API documentation.