I am pretty new to writing XSLT transformation logic's so can someone help me out here please.
I am working on XML to XML transformation using XSLT and the idea was to insert missing elements.
Input XML:
<EmpJob>
<EmpJob>
<emplStatus>3805</emplStatus>
<lastName>Jhonny</lastName>
<firstName>English</firstName>
<EmpJobRelationships>
<relUserNav>
<User>
<defaultName>Crystal</defaultName>
<userId>00174941</userId>
</User>
</relUserNav>
</EmpJobRelationships>
</EmpJob>
<EmpJob>
<emplStatus>3805</emplStatus>
<lastName>Tony</lastName>
<firstName>Romo</firstName>
</EmpJob>
<EmpJob>
Desired XML Output with XSLT transformation
<EmpJob>
<EmpJob>
<emplStatus>3805</emplStatus>
<lastName>Johnny</lastName>
<firstName>English</firstName>
<EmpJobRelationships>
<relUserNav>
<User>
<defaultName>Crystal</defaultName>
<userId>00174941</userId>
</User>
</relUserNav>
</EmpJobRelationships>
</EmpJob>
<EmpJob>
<emplStatus>3805</emplStatus>
<lastName>Tony</lastName>
<firstName>Romo</firstName>
<EmpJobRelationships>
<relUserNav>
<User>
<defaultName></defaultName>
<userId></userId>
</User>
</relUserNav>
</EmpJobRelationships>
</EmpJob>
<EmpJob>
I tired the below XSLT but the missing elements is once added at the end of the first Parent but it want it to happen on each of the child . How do I put the logic into a loop so it happens on each of the child
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*[not(//EmpJobRelationships)]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<EmpJobRelationships>
<relationshipType></relationshipType>
<relUserNav>
<User>
<defaultFullName></defaultFullName>
<userId></userId>
</User>
</relUserNav>
<userId></userId>
<startDate></startDate>
</EmpJobRelationships>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Thanks
CodePudding user response:
Assuming that the "missing element" is EmpJobRelationships and that it's either present or missing entirely, try:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/EmpJob/EmpJob[not(EmpJobRelationships)]">
<xsl:copy>
<xsl:apply-templates/>
<EmpJobRelationships>
<relUserNav>
<User>
<defaultName/>
<userId/>
</User>
</relUserNav>
</EmpJobRelationships>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Note the match pattern /EmpJob/EmpJob designed to prevent applying the template to the root element of the same name.
