Same column with a different name is invalid SQL, you need to select both conditions as separate columns:
;WITH XMLNAMESPACES
(
'http://www.w3.org/2001/XMLSchema-instance' AS abc, 'uri' AS def
)
SELECT
(
SELECT 'BUYER'
FROM
ACCOUNTS a
WHERE AGE <=30
FOR XML PATH ('def:GIRL'),TYPE
),
( SELECT 'SELLER'
FROM
ACCOUNTS
WHERE AGE >=40
FOR XML PATH ('def:BOY'), TYPE
)
FOR XML PATH ('abc:OilCompany'),TYPE
Unfortunely this solution pushses the xml namespaces into every element.
The best way to avoid this, as per this anwser https://stackoverflow.com/questions/3242070/how-do-i-remove-redundant-namespace-in-nested-query-when-using-for-xml-path seems to be stepping in to the not so wonderful world of XML EXPLICIT
Leaving us with:
SELECT
1 AS Tag
,NULL AS Parent
,'http://www.w3.org/2001/XMLSchema-instance' AS [abc:OilCompany!1!xmlns:abc]
,'uri' AS [abc:OilCompany!1!xmlns:def]
,NULL as [def:GIRL!2]
,NULL as [def:BOY!3]
UNION ALL
SELECT
2 as Tag
,1 as Parent
,NULL
,NULL
,'BUYER' as [def:GIRL!2]
,NULL
FROM
ACCOUNTS
WHERE AGE <= 30
UNION ALL
SELECT
3 as Tag
,1 as Parent
,NULL
,NULL
,NULL
,'SELLER' as [def:BOY!3]
FROM
ACCOUNTS
WHERE AGE >= 40
FOR XML EXPLICIT
Both of these solutions also cause 2 scans on the same table - simplified in explicit:
SELECT
1 AS Tag
,NULL AS Parent
,'http://www.w3.org/2001/XMLSchema-instance' AS [abc:OilCompany!1!xmlns:abc]
,'uri' AS [abc:OilCompany!1!xmlns:def]
,NULL as [def:GIRL!2]
,NULL as [def:BOY!3]
UNION ALL
SELECT
CASE WHEN AGE <= 30 THEN 2
WHEN AGE >= 40 THEN 3 END as Tag
,1 as Parent
,NULL
,NULL
,CASE WHEN AGE <= 30 THEN 'BUYER' ELSE NULL END as [def:GIRL!2]
,CASE WHEN AGE >= 40 THEN 'SELLER' ELSE NULL END as [def:BOY!3]
FROM
ACCOUNTS
WHERE AGE <=30 OR AGE >=40 -- required if there are other rows in the source table
FOR XML EXPLICIT