Using XSLT, I am trying to figure out how to merge/update the data in a set of nodes with data from another set of nodes. The nodes have the same schema, but different parents. The data needs to be merged based on a shared parent attribute. In the example below, data is being copied from Principal to Driver. Can anyone help me out here?
Input File:
<Info>
<Principal id="Insured">
<PersonName>
<GivenName>Jane</GivenName>
<OtherGivenName>A</OtherGivenName>
<Surname>Doe</Surname>
</PersonName>
<PersonInfo>
<BirthDate>01-01-1980</BirthDate>
<MaritalStatus>M</MaritalStatus>
</PersonInfo>
<PrincipalInfo></PrincipalInfo>
</Principal>
<Policy>
<Driver id="Insured">
<PersonName>
<GivenName>Jane</GivenName>
<Surname>Smith</Surname>
</PersonName>
<PersonInfo>
<BirthDate>01-01-1980</BirthDate>
<MaritalStatus>S</MaritalStatus>
<Occupation>Manager</Occupation>
</PersonInfo>
</Driver>
<PolicyInfo></PolicyInfo>
</Policy>
</Info>
Desired Result:
<Info>
<Principal id="Insured">
<PersonName>
<GivenName>Jane</GivenName>
<OtherGivenName>A</OtherGivenName>
<Surname>Doe</Surname>
</PersonName>
<PersonInfo>
<BirthDate>01-01-1980</BirthDate>
<MaritalStatus>M</MaritalStatus>
</PersonInfo>
<PrincipalInfo></PrincipalInfo>
</Principal>
<Policy>
<Driver id="Insured">
<PersonName>
<GivenName>Jane</GivenName>
<OtherGivenName>A</OtherGivenName>
<Surname>Doe</Surname>
</PersonName>
<PersonInfo>
<BirthDate>01-01-1980</BirthDate>
<MaritalStatus>M</MaritalStatus>
<Occupation>Manager</Occupation>
</PersonInfo>
</Driver>
<PolicyInfo></PolicyInfo>
</Policy>
</Info>
Here is a complete solution:
when this transformation is applied on the provided XML document:
the wanted, correct result is produced:
Explanation:
The identity rule/template copies every node “as-is”. The use and overriding of the identity rule is the most fundamental and powerful XSLT design pattern.
There is just one additional template that overrides the identity rule for children-elements of
Driver. It copies (and effectively replaces the same-named grand-child elements ofDriverwith the corresponding) grand-child elements ofPrincipal. Then it still processes (copies) those grand-children elements ofDriverthat do not have corresponding grand-children elements ofPrincipalFor convenient access to
Principaland its grand-children — by id and id++name(), there are two keys defined and used.