For those interested, solution consisted of putting the union query into a CTE.
declare @head1 table
(head_id uniqueidentifier)
declare @sub1 table (
head_id uniqueidentifier,
own_id int,
own_field nvarchar(20))
declare @sub2 table (
head_id uniqueidentifier,
own_id int,
own_field nvarchar(20))
declare @unrelated table (
head_id uniqueidentifier,
own_id int,
own_field nvarchar(20))
declare @gd uniqueidentifier;
set @gd = newid();
insert into @head1 (head_id) values (@gd)
insert into @sub1 (head_id,own_id,own_field) values (@gd,10,'Sub1 field')
insert into @sub2 (head_id,own_id,own_field) values (@gd,11,'Sub2 field')
insert into @unrelated (head_id,own_id,own_field) values (@gd,100,'another field');
with subs (head_id,own_id,own_field)
as
( select sub1.head_id,sub1.own_id,sub1.own_field
from @sub1 sub1
union all
select sub2.head_id,sub2.own_id,sub2.own_field
from @sub2 sub2
)
select head.head_id
,( select * from subs where subs.head_id = head.head_id for xml path('sub'),type )
,(select unrelated.own_id,unrelated.own_field
from @unrelated unrelated where unrelated.head_id = head.head_id
for xml path('unrelated'),type )
from @head1 head
for xml auto,root('master')
Kudos to https://www.sqlservercentral.com/Forums/Users/Eirikur-Eiriksson