XSLT: Add node, if it is missing, in a specific place in output XML



I'm trying to build a transformation that will:



  • Add a "default" node, if that node is found not to exist within an instance of a parent

  • Add that default node in a specific place in the output XML


For example, if "Age" is not provided for a person then it should be defaulted to "Unknown" in the node following the required "Name" node:



<People>
<Person>
<Name>Bob Smith</Name>
<Age>34</Age>
<Gender>Male></Gender>
</Person>
<Person>
<Name>Jane Smith</Name>
<Gender>Female</Gender>
</Person>
</People>


Becomes:



<People>
<Person>
<Name>Bob Smith</Name>
<Age>34</Age>
<Gender>Male></Gender>
</Person>
<Person>
<Name>Jane Smith</Name>
<Age>Unknown</Age>
<Gender>Female</Gender>
</Person>
</People>


I have the following XSLT, which correctly adds the default, but it adds the default to the end of the Person section. I need the node to be added just after the Name node:



<xsl:stylesheet version="1.0"
xmlns:xsl="http://ift.tt/tCZ8VR"
xmlns:p="http://ift.tt/1tABcLP">
<xsl:output omit-xml-declaration="yes" indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="Person[not(Age)]">
<Person>
<xsl:apply-templates select="node()|@*" />
<Age>Unknown</Age>
</Person>
</xsl:template>
</xsl:stylesheet>


Could anyone help me implement the additional requirement for the "Age" node to be added after the 'Name" node?


Many thanks!


No comments:

Post a Comment