I have been searching StackOverflow for a while yet unsuccessful. My aim is to filter Employee XML documents. The Input XML has around 9000 Employees, and I have multiple target systems who wants a subset of these Employee Records based on different selection criteria for each target system. Sample Input:
<Employees>
<Employee>
<id>1</id>
<name>Name1</name>
</Employee>
<Employee>
<id>2</id>
<name>Name2</name>
</Employee>
<Employee>
<id>3</id>
<name>Name3</name>
</Employee>
<Employee>
<id>4</id>
<name>Name4</name>
</Employee>
</Employees>
The output should be of the same structure but reduced nodes based on the selection criteria(XPATH). How can I pass the dynamic XPath to an XSLT stylesheet and get the filtered employees as output? Please note the complete Xpath Expression along with the filtering conditions are passed as one string.
Desired output:
<Employees>
<Employee>
<id>2</id>
<name>Name2</name>
</Employee>
<Employee>
<id>3</id>
<name>Name3</name>
</Employee>
</Employees>
CodePudding user response:
With XSLT 3.0, xsl:evaluate
for dynamic XPath evaluation. You could accept the XPath as an xsl:param
(shown with an example default XPath value) and then evaluate it.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
<xsl:output indent="yes"/>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:param name="path" select="'/Employees/Employee[number(id)[. gt 1 and . lt 4]]'" />
<xsl:template match="Employees">
<xsl:copy>
<xsl:evaluate xpath="$path" context-item="."/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>