Thursday, September 26, 2013

XSLT : Filter Child node based on Parent node value

This blog post will help you to filter child node elements based on parent node values in XSL transformation.

Given solution will help you to create master and detail relationship, when you are getting parent and child data from different sources.

Simple steps:

  • Create a variable to hold a key value from parent node to identify child nodes.(Note: The variable declared immediately after for-each tag in given sample XSLT)
  • Refer that variable value in child node to filter the results.

Sample XSLT with solution to filter employees node results by department ID:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- SOURCE 1 - Departments Data. -->
    <source type="XSD">
      <schema location="../xsd/DEPARTMENTS.xsd"/>
      <rootElement name="OutputParameters" namespace=""/>
<!-- SOURCE 2 - Employees Data. -->
    <source type="XSD">
      <schema location="../xsd/EMPLOYEES.xsd"/>
      <rootElement name="OutputParameters" namespace=""/>
      <param name="varGetEmployeesDBAdapterOutput.OutputParameters" />
    <target type="XSD">
      <schema location="../xsd/QueryDept.xsd"/>
      <rootElement name="QueryEmpResponse" namespace=""/>
<xsl:stylesheet version="1.0"
                exclude-result-prefixes="xsi xsl db ns0 ns1 xsd tns xp20 bpws aia mhdr bpel oraext dvm hwf med ids bpm xdk xref bpmn ora socket ldap">
  <xsl:param name="varGetEmployeesDBAdapterOutput.OutputParameters"/>
  <xsl:template match="/">
        <xsl:for-each select="/db:OutputParameters/db:OUT_DEPT_CUR/db:OUT_DEPT_CUR_Row">
          <xsl:variable name="DeptID" select="db:DEPT_ID"/>
                <xsl:value-of select="db:DEPT_ID"/>
                <xsl:value-of select="db:DEPT_NAME"/>
              <xsl:for-each select="$varGetEmployeesDBAdapterOutput.OutputParameters/ns1:OutputParameters/ns1:OUT_EMPLOYEE_CUR/ns1:OUT_EMPLOYEE_Row[(ns1:DEPT_ID = $DeptID)]">
                    <xsl:value-of select="ns1:EMPLOYEE_ID"/>
                    <xsl:value-of select="ns1:EMPLOYEE_NAME"/>

1 comment:

Provide your thoughts !