I've changed to using XML PATH now which gives better results, but still not perfect.
SELECT TOP 5
CT.ID AS [ID]
,CT.TITLE AS [Title]
,CT.TELEPHONE AS [Tel]
,AD.LINE1 AS [Addresses/Address/Line1]
FROM CONTACT CT
INNER JOIN METADATA MD ON CT.CONTACTID = MD.OWNERID
INNER JOIN ADDRESS AD ON MD.TOOWNERID = AD.ADDRESSID
WHERE CT.ID IS NOT NULL
FOR XML PATH ('ContactDetails'), root ('LeanerData');
Results in multiple Contact nodes as seen here ID 539091 is repeated twice :
<Records>
<Contact>
<ID>535317</ID>
<Tel>7859243561</Tel>
<Home>1</Home>
<Addresses>
<Address>
<Line1>Address 1</Line1>
</Address>
</Addresses>
</Contact>
<Contact>
<ID>539091</ID>
<Tel>9876543231</Tel>
<Home>0</MobileTel>
<Addresses>
<Address>
<Line1>Address 3</Line1>
</Address>
</Addresses>
</Contact>
<Contact>
<ID>539091</ID>
<Tel>9876543231</Tel>
<Home>0</MobileTel>
<Addresses>
<Address>
<Line1>Address 4</Line1>
</Address>
</Addresses>
</Contact>
</Records>
I am trying to get this particular format.
<Records>
<Contact>
<ID>535317</ID>
<Tel>7859243561</Tel>
<Home>1</Home>
<Addresses>
<Address>
<Line1>Address 1</Line1>
</Address>
</Addresses>
</Contact>
<Contact>
<ID>539091</ID>
<Tel>9876543231</Tel>
<Home>0</MobileTel>
<Addresses>
<Address>
<Line1>Address 3</Line1>
</Address>
<Address>
<Line1>Address 4</Line1>
</Address>
</Addresses>
</Contact>
</Records>
FOR XML PATHis generally much easier to use if it's available to you.FOR XML PATH,TYPE.EXPLICITis the worst way to generate XML.