I need to transform an XML file by adding a new element that will have a value based on data in the current file and two other XML files using XSLT 1.0. The files:
File1:
<Table>
<Row>
<ColA>AValue1</ColA>
<ColB>BValue1</ColB>
</Row>
<Row>
<ColA>AValue2</ColA>
<ColB>BValue2</ColB>
</Row>
</Table>
File2:
<Table>
<Row>
<ColA>AValue1</ColA>
<ColB>BValue1</ColB>
<ColC>CValue1</ColC>
</Row>
<Row>
<ColA>AValue1</ColA>
<ColB>BValue1</ColB>
<ColC>CValue1</ColC>
</Row>
<Row>
<ColA>AValue1</ColA>
<ColB>BValue1</ColB>
<ColC>CValue2</ColC>
</Row>
<Row>
<ColA>AValue1</ColA>
<ColB>BValue1</ColB>
<ColC>CValue3</ColC>
</Row>
<Row>
<ColA>AValue2</ColA>
<ColB>BValue2</ColB>
<ColC>CValue1</ColC>
</Row>
</Table>
File3:
<Table>
<Row>
<ColC>CValue1</ColC>
<ColD>ABC</ColD>
</Row>
<Row>
<ColC>CValue2</ColC>
<ColD>DEF</ColD>
</Row>
<Row>
<ColC>CValue3</ColC>
<ColD>DEF</ColD>
</Row>
</Table>
Rows in File1 have a one-to-many relationship with rows in File2 by ColA and ColB.
Rows in File2 have a many-to-one relationship with rows in File3 by ColC.
For each row in File1, I need to:
-
Look up distinct ColC values in File2 for rows matching on ColA and ColB
-
For each distinct ColC value, look up ColD value in File3 for rows matching on ColC
-
Count the number of occurences of ColD values looked up in step 2. ColD will have one of two values (say “ABC” or “DEF”). I need to know if there are more “ABC” than “DEF” and if so add <ColD>ABC</ColD> to that Row in File1. Otherwise add <ColD>DEF</ColD> to that Row in File1. At the end, each Row in File1 should have <ColD>ABC</ColD> or <ColD>DEF</ColD>.
Desired Result (File1 transformed):
<Table>
<Row>
<ColA>AValue1</ColA>
<ColB>BValue1</ColB>
<ColD>DEF</ColD>
</Row>
<Row>
<ColA>AValue2</ColA>
<ColB>BValue2</ColB>
<ColD>ABC</ColD>
</Row>
</Table>
<ColD>DEF</ColD> would be added to the first Row since there were two occurences of DEF compared to 1 (distinct) occurence of ABC. <ColD>ABC</ColD> would be added to Row 2 since there was one occurence of ABC and zero DEF.
I came up with a solution that appears to work (haven’t tested it very much). I’m retyping it here so beware of typos. The thing I had the hardest time with was figuring out how to select unique ColC values. Looking at the solution again I didn’t need unique values. I had it in my mind that I would loop thru $unique_c_values to count ColD values, but it turned out differently.