Example: Filtering Nodes
This example shows you how to filter nodes based on a true/false condition. A Filter: Nodes/Rows ( ) component is used to achieve this goal.
The mapping described in this example is available at the following path: <Documents>\Altova\MapForce2022\MapForceExamples\MarketingExpenses.mfd.
As shown above, the mapping reads data from a source XML which contains an expense report ("ExpReport") and writes data to a target XML ("MarketingExpenses"). There are several other components between the target and source. The most relevant component is the expense-item filter ( ), which represents the subject of this topic.
The goal of the mapping is to filter out only those expense items that belong to the Marketing department. To achieve this goal, a filter component has been added to the mapping. (To add a filter, click the Insert menu, and then click Filter: Nodes/Rows.)
To identify whether each expense item belongs to Marketing, this mapping looks at the value of the "expto" attribute in the source. This attribute has the value "Marketing" whenever the expense is a marketing expense. For example, in the code listing below, the first and third expense item belongs to Marketing, the second belongs to Development, and the fourth belongs to Sales:
<expense-item type="Meal" expto="Marketing">
XML input before the mapping is executed
On the mapping area, the node/row input of the filter is connected to the expense-item node in the source component. This ensures that the filter component gets the list of nodes that it must process.
To add the condition based on which filtering should occur, we have added the equal function from the MapForce core library, see also Add a Function to the Mapping. The equal function compares the value of the expto attribute to a constant which has the value Marketing. (To add a constant, click the Insert menu, and then click Constant.)
Since we need to filter only those items that satisfy the condition, we connected only the on-true output of the filter to the target component.
When you preview the mapping result, by clicking the Output tab, MapForce evaluates, for each expense-item node, the condition connected to the bool input of the filter. When the condition is true, the expense-item node is passed on to the target; otherwise, it is ignored. Consequently, only the expense items matching the criteria are displayed in the output:
XML output after the mapping is executed