How to query on XML column in SQL Server? - sql-server

I have a table named "Table1" and in the table there are columns titled "Name" and "XMLDefinition".
Name XMLDefinition
--------------------------
Name1 xmlLink1
Name2 xmlLink2
Inside each XML an example would look similar to this below:
<Query xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<QueryView>
<QueryKey />
</QueryView>
<Description>
</Description>
<QueryFields>
<f />
<f />
</QueryFields>
<FilterFields>
<f ObjectName="TABLE5" ColumnName="ID">
<DateFilterTypes />
<FuzzyDateFilterTypes />
<MonthDayFilterTypes />
<Values>
<v>0</v>
</Values>
<TranslatedValues>
<v>No</v>
</TranslatedValues>
<DataType>Boolean</DataType>
</f>
<f ObjectName="TABLE2" ColumnName="USERID">
<DateFilterTypes />
<FuzzyDateFilterTypes />
<MonthDayFilterTypes />
<Values>
<v>B80055</v>
</Values>
<TranslatedValues>
<v>B80055</v>
</TranslatedValues>
<DataType>String</DataType>
</f>
</FilterFields>
</Query>
I'd like to return Name from TABLE1 as long as in the XML content contains where ObjectName = "TABLE2" AND ColumnName = "USERID".
I have tried the below and while it doesn't error out, it returns 0 records:
SELECT
a.Name,
X.Y.value('(f)[1]', 'VARCHAR(MAX)') as Object
FROM TABLE1 a
OUTER APPLY a.XMLDefinition.nodes('Query/FilterFields/f') as X(Y)
WHERE X.Y.value('(ObjectName)[1]', 'VARCHAR(MAX)') = 'TABLE2'
AND X.Y.value('(ColumnName)[1]', 'VARCHAR(MAX)') = 'USERID'
I'm not sure what I am missing as it seems I am drilling down from Query > FilterFields > f and I assume I'd be able to then filter based on the ObjectName and ColumnName here.
Attempt 2 Update:
SELECT Name from TABLE1
WHERE XMLDefinition.value('(/Query/QueryView/Description/QueryFields/FilterFields/f/#ObjectName) [1] ',' varchar(max)') = 'TABLE2'
AND XMLDefinition.value('(/Query/QueryView/Description/QueryFields/FilterFields/f/#ColumnName) [1] ',' varchar(max)') = 'USERID'
After trying this attempt by drilling through each tag, it is still giving me 0 results.
Attempt 3 Update:
select
a.Name,
X.Y.query(N'.') as [Object] --this returns the XML of the <f> element
from dbo.Table1 a
cross apply a.XMLDefinition.nodes('//*:f[#ObjectName="TABLE2"][#ColumnName="USERID"][1]') as X(Y);
I'm not sure why, but I tried this and now it worked and returned the results that I was looking for. I'm new to XML, but I assume this worked because it ignored all the namespaces and prior tags before the f tag?

The code below probably does what you're looking for. Note that cross apply will only return dbo.Table rows that matched the XPath query, as opposed to outer apply which will return all dbo.Table rows but only XML-derived values for those rows that matched the XPath query:
create table dbo.Table1 (
Name nvarchar(10),
XMLDefinition xml
);
insert dbo.Table1 (Name, XMLDefinition) values
(N'Name1', N'<xmlLink1 />'),
(N'Name2', N'<Query xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FilterFields>
<f ObjectName="TABLE2" ColumnName="USERID" ParentPath="TABLE2" DisplayPath="TABLE2" CompareType="Or" UseLeftParenthesis="true" LeftParenthesisCount="1" IncludeCurrentNode="true">
<DateFilterTypes />
<FuzzyDateFilterTypes />
<MonthDayFilterTypes />
<Values>
<v>B80055</v>
</Values>
<TranslatedValues>
<v>B80055</v>
</TranslatedValues>
<DataType>String</DataType>
</f>
</FilterFields>
</Query>');
select
a.Name,
X.Y.query(N'.') as [Object] --this returns the XML of the <f> element
from dbo.Table1 a
cross apply a.XMLDefinition.nodes(N'/Query/FilterFields/f[#ObjectName="TABLE2"][#ColumnName="USERID"][1]') as X(Y);

Related

How to filter xml data type column in SQL Server

I have a table with two xml columns and the data inside the table is large. I would like to filter on the column which is of xml type to check if it contains a ID.
My sample xml column IncomingXML and value looks like this:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sws="abc">
<soapenv:Header>
<To xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" soapenv:mustUnderstand="1">abc</To>
<Action xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" soapenv:mustUnderstand="1">student</Action>
</soapenv:Header>
<soapenv:Body>
<sws:ProvisionStudent>
<sws:provisionStudentInput>
<sws:Operation>U</sws:Operation>
<sws:ADAccount>SU123456789</sws:ADAccount>
<sws:ADPassword>abcde</sws:ADPassword>
<sws:Prefix />
<sws:FirstName>ancd</sws:FirstName>
<sws:LastName>xyz</sws:LastName>
<sws:MiddleName />
<sws:Suffix />
<sws:Email>abc#yahoo.com</sws:Email>
<sws:EmplId>123456789</sws:EmplId>
<sws:CampusCode />
<sws:CompletionYear>0</sws:CompletionYear>
<sws:CurrentCumulativeGpa>0</sws:CurrentCumulativeGpa>
<sws:GraduationGpa />
<sws:GraduationProgramCode />
<sws:ProgramCode />
<sws:UserType />
</sws:provisionStudentInput>
</sws:ProvisionStudent>
</soapenv:Body>
</soapenv:Envelope>
Please help me with a query like
select *
from table
where IncomingXML like '%SU123456789%'
I tried the following but did not have any luck.
select *
from table
where cast(IncomingXML as nvarchar(max)) like '%SU123456789%'
You can use XQuery for this
DECLARE #toSearch nvarchar(100) = 'SU123456789';
WITH XMLNAMESPACES(
'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv,
DEFAULT 'abc'
)
SELECT *
FROM YourTable t
WHERE t.IncomingXML.exist('/soapenv:Envelope/soapenv:Body/ProvisionStudent/provisionStudentInput/ADAccount[text() = sql:variable("#toSearch")]') = 1;
To search in any node, at the cost of efficiency
DECLARE #toSearch nvarchar(100) = 'SU123456789';
SELECT *
FROM YourTable t
WHERE t.IncomingXML.exist('//*[text() = sql:variable("#toSearch")]') = 1;
db<>fiddle
You can obviously also embed a literal instead of a variable in the XQuery.

SQL Server FOR XML with nested sub-select

The following sql code
SELECT
b.GivenName [Individual/Name/FirstName] ,
b.FamilyName [Individual/Name/LastName] ,
b.Address_Country [Individual/Address/CountryCode] ,
b.AddressFree [Individual/Address/AddressFree]
FROM dbo.stage_Clients_Merge b
WHERE b.DWHClientNo = #dwhclientNo
FOR XML PATH('Owner'), TYPE
will generate an xml fragment
<Owner>
<Individual>
<Name>
<FirstName>Bob</FirstName>
<LastName>Smith</LastName>
</Name>
<Address>
<CountryCode>US</CountryCode>
<AddressFree>123,Utah</AddressFree>
</Address>
</Individual>
</Owner>
If I extend this query to include a sub-query to return, for example, all the orders associated with a individual using the following:
(SELECT
c.OrderIdentificationNumber [Individual/OrderNumber]
FROM
dbo.stage_Customer_Orders c
WHERE
c.CustomerNo = b.masterClient
FOR
XML PATH(''), TYPE)
I will get the individual section twice. How can I combine the two to return the following?
<Owner>
<Individual>
<OrderNo>12345</OrderNo>
<OrderNo>23456</OrderNo>
<Name>
<FirstName>Bob</FirstName>
<LastName>Smith</LastName>
</Name>
<Address>
<CountryCode>US</CountryCode>
<AddressFree>123,Utah</AddressFree>
</Address>
</Individual>
</Owner>
Try it like this
I set up a mock-up scenario for stand-alone solutions. Next time you have a question, you might try this on your own. This makes it much easier to understand your issue and create a fully working and testable solution for it.
DECLARE #stage_Clients_Merge TABLE(ID INT,FirstName VARCHAR(100),LastName VARCHAR(100),CountryCode VARCHAR(100),AdressFree VARCHAR(100));
INSERT INTO #stage_Clients_Merge VALUES
(1,'Bob','Smith','US','123/Utah')
,(2,'Jim','Doh','US','123/Maryland');
DECLARE #orders TABLE(CustomerID INT, OrderNo INT)
INSERT INTO #orders VALUES
(1,11111),(1,12222)
,(2,21111),(2,22222);
SELECT (SELECT OrderNo FROM #orders WHERE CustomerID=b.ID FOR XML PATH(''),TYPE) AS Individual
,FirstName AS [Individual/Name/FirstName]
,LastName AS [Individual/Name/LastName]
,CountryCode AS [Individual/Address/CountryCode]
,AdressFree AS [Individual/Address/AdressFree]
FROM #stage_Clients_Merge AS b
FOR XML PATH('Owner');
You can use a subquery and [data()] to just get the column values with no additional nesting - then use path as before:
SELECT
(SELECT c.OrderIdentificationNumber as [data()]
FROM dbo.stage_Customer_Orders c
WHERE c.CustomerNo = b.masterClient
For XML Path('OrderNo'), type) as [Individual],
b.GivenName [Individual/Name/FirstName] ,
b.FamilyName [Individual/Name/LastName] ,
b.Address_Country [Individual/Address/CountryCode] ,
b.AddressFree [Individual/Address/AddressFree]
FROM dbo.stage_Clients_Merge b
WHERE b.DWHClientNo = #dwhclientNo
FOR XML PATH('Owner'), TYPE

SQL Server WHERE clause XPath with multiple nodes and conditions

I have this XML in a table column in SQL Server:
<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Lead</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Shikasta</FirstName>
<LastName>Kashti</LastName>
<MessageId>1347_1483825159115_c8273</MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>
I want to query all the records where it matches some nodes with specific values. For example I want all records where LeadDispositionID=Lead and Jurisdiction=NY and CampaignOfferTypeID=REN and a MessageId element exists (doesn't matter what value.)
I tried this but it doesn't work (no errors but the conditions doesn't match and it returns other records):
SELECT TOP 10 *
FROM [Messages]
WHERE PayLoadXml.exist('//LeadDispositionID[.="Lead"] and //CampaignOfferTypeID[.="REN"] and //Jurisdiction[.="NY"] and //MessageId') = 1
ORDER BY ID DESC
Any idea as to what I'm doing wrong?
You cannot combine nodes within .exist() simply with and. Your own example would work like this:
SELECT TOP 10 *
FROM #Messages
WHERE PayLoadXml.exist('//VendorLeadItem[LeadDispositionID[.="Lead"] and CampaignOfferTypeID[.="REN"] and Jurisdiction[.="NY"] and MessageId/text()]') = 1
Try it like this:
First a declared table to mock-up your Messages table. Insert 3 cases:
DECLARE #messages TABLE(SomeDescription VARCHAR(100),PayLoadXml XML);
INSERT INTO #messages VALUES
('Your example'
,'<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Lead</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Shikasta</FirstName>
<LastName>Kashti</LastName>
<MessageId>1347_1483825159115_c8273</MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>'
)
,('LeadDispositionID=Slave'
,'<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Slave</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Bruno</FirstName>
<LastName>Kashti</LastName>
<MessageId>1347_1483825159115_c8273</MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>'
)
,('LeadDispositionID=Lead but No MessageId'
,'<root>
<Request>
<RequestData>
<VendorLeadList>
<VendorLeadItem>
<CampaignOfferTypeID>REN</CampaignOfferTypeID>
<LeadDispositionID>Lead</LeadDispositionID>
<Jurisdiction>NY</Jurisdiction>
<FirstName>Bruno</FirstName>
<LastName>Kashti</LastName>
<MessageId></MessageId>
</VendorLeadItem>
</VendorLeadList>
</RequestData>
<DualMessageID/>
<AzureBlobFile/>
<AzureBlobImageList/>
</Request>
</root>'
);
This is the query:
The CROSS APPLY will ensure, that only nodes with a MessageId are taken into account. The WHERE will apply an additional filter
SELECT m.*
FROM #messages AS m
CROSS APPLY m.PayLoadXml.nodes(N'/root/Request/RequestData/VendorLeadList/VendorLeadItem[not(empty(MessageId/text()))]') AS A(itm)
WHERE itm.exist(N'LeadDispositionID[text()="Lead"]')=1
If you need to check more than one condition you might use this:
WHERE itm.exist(N'.[LeadDispositionID="Slave" and FirstName="Bruno"]')=1

CROSS APPLY to namespace, sub nodes returns duplicate records

I have this xml (removed most of it for readability). I get wrong records. Wrong chemical names fetched for every CAS_Number. One CAS_Number means one chemical. But here, for the same CAS_number, I have different chemical names.
It's the problem in my cross apply but I couldn't figure it out.
<ArrayOfCatalogItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CatalogItem Version="1">
<Msds xmlns="http://3ecompany.com/webservices/catalogitemxml">
<ProductIdentifiers xmlns="http://3ecompany.com/webservices/catalogitemxml">
<Identifier>M007628</Identifier>
<Source>CPN</Source>
<FirstExportDate xsi:nil="true" />
<LastExportDate xsi:nil="true" />
<FlaggedForResend xsi:nil="true" />
</ProductIdentifiers>
<Ingredients>
<ChemicalName>Hexane</ChemicalName>
<Cas>000110-54-3</Cas>
<AvgPercent>20.000000</AvgPercent>
</Ingredients>
<Ingredients>
<ChemicalName>2-Propanone</ChemicalName>
<Cas>000067-64-1</Cas>
<AvgPercent>20.000000</AvgPercent>
</Ingredients>
<Ingredients>
<ChemicalName>Petroleum gases, liquefied, sweetened</ChemicalName>
<Cas>068476-86-8</Cas>
</Ingredients>
</Msds>
</CatalogItem>
</ArrayOfCatalogItem>
The stored procedure goes like this:
DECLARE #XmlTable TABLE (XMLDATA XML)
INSERT INTO #XmlTable(XMLData)
SELECT CONVERT(XML, BulkColumn) AS BulkColumn
FROM OPENROWSET(BULK 'C:\AA.Sample.File.LUS.Pilly-oneCI.xml', SINGLE_BLOB) AS x;
;WITH XMLNAMESPACES ('http://3ecompany.com/webservices/catalogitemxml' as CI)
SELECT
--CIVersion = CI.value('#Version', 'int'),
Identifier = PID.value('(.)\[1\]', 'varchar(9)'),
Product_Name = MSDSPN.value('(.)\[1\]','varchar(100)'),
CAS_Number = CAS.value('(.)\[1\]', 'varchar(20)'),
Chemical_Name = CN.value('(.)\[1\]', 'varchar(100)')
FROM
#XmlTable
CROSS APPLY
XMLData.nodes('/ArrayOfCatalogItem/CatalogItem') AS XT(CI)
OUTER APPLY
CI.nodes('CI:ProductIdentifiers/CI:Identifier') AS XT2(PID)
CROSS APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:Cas') AS XT18(CAS)
CROSS APPLY
CI.nodes('CI:Msds/CI:Ingredients/CI:ChemicalName') AS XT19(CN)
Try this:
;WITH XMLNAMESPACES ('http://3ecompany.com/webservices/catalogitemxml' as CI)
SELECT
Identifier = CI.value('(CI:ProductIdentifiers[1]/CI:Identifier)[1]', 'varchar(9)'),
CAS_Number = Ingred.value('(CI:Cas)[1]', 'varchar(20)'),
Chemical_Name = Ingred.value('(CI:ChemicalName)[1]', 'varchar(100)')
FROM
#XmlTable
CROSS APPLY
XMLData.nodes('/ArrayOfCatalogItem/CatalogItem/CI:Msds') AS XT(CI)
CROSS APPLY
CI.nodes('CI:Ingredients') AS XT18(Ingred)
I get a list of XML fragments for each <Msds> node, and from this I grab the ProductIdentifiers info. Plus, from this node, I also get a list of sub-XML-fragments for the <Ingredients> nodes, and grab detailed into from these.
My output looks like this:

CTE and FOR XML to generate nested XML

I have an adjacency list in the DB and want to deliver the data in XML format to the client through a SQL SP. I'm trying to use CTE and FOR XML but I am not getting the XML nodes to nest.
FYI, this will represent a site map.
The Table structure:
CREATE TABLE [dbo].[PageHierarchy](
[ModuleId] [int] NOT NULL,
[PageId] [int] IDENTITY(1,1) NOT NULL,
[ParentPageId] [int] NULL,
[PageUrl] [nvarchar](100) NULL,
[PageTitle] [nvarchar](50) NOT NULL,
[PageOrder] [int] NULL)
and the beginnings of the CTE:
;WITH cte AS
(
select * from PageHierarchy where ParentPageId is null
union all
select child.* from PageHierarchy child inner join cte parent on parent.PageId = child.ParentPageId
)
SELECT ModuleId, PageId, ParentPageId, PageUrl, PageTitle, PageOrder FROM cte
group by ModuleId, PageId, ParentPageId, PageUrl, PageTitle, PageOrder
order by PageOrder
for xml auto, root ('bob')
yields XML that looks like this:
<bob>
<cte ModuleId="1" PageId="1" PageUrl="~/Admin/" PageTitle="Administration" PageOrder="1000" />
<cte ModuleId="1" PageId="4" ParentPageId="1" PageTitle="Manage Users" PageOrder="1030" />
<cte ModuleId="1" PageId="5" ParentPageId="4" PageUrl="~/Admin/AddUser" PageTitle="Add Users" PageOrder="1040" />
<cte ModuleId="1" PageId="8" ParentPageId="4" PageUrl="~/Admin/EditUser" PageTitle="Edit/Search User" PageOrder="1070" />
</bob>
when what I want is XML that looks like this:
<bob>
<cte ModuleId="1" PageId="1" PageUrl="~/Admin/" PageTitle="Administration" PageOrder="1000" />
<cte ModuleId="1" PageId="4" ParentPageId="1" PageTitle="Manage Users" PageOrder="1030" >
<cte ModuleId="1" PageId="5" ParentPageId="4" PageUrl="~/Admin/AddUser" PageTitle="Add Users" PageOrder="1040" />
<cte ModuleId="1" PageId="8" ParentPageId="4" PageUrl="~/Admin/EditUser" PageTitle="Edit/Search User" PageOrder="1070" />
</cte>
</bob>
I'm guessing the issue is not with the CTE but with the select, but I don't know where to start to fix it. Also, I don't know how deep the nesting will go, so I'm assuming I'll need it to support at least 10 levels deep.
Edit 1:
I think I'm getting closer... in looking at this page, I created a UDF but still there are some issues:
CREATE FUNCTION PageHierarchyNode(#PageId int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN
(SELECT ModuleId AS "#ModuleId", PageId AS "#PageId",
ParentPageId AS "#ParentPageId", PageUrl AS "#PageUrl",
PageTitle AS "#PageTitle", PageOrder AS "#PageOrder",
CASE WHEN ParentPageId=#PageId
THEN dbo.PageHierarchyNode(PageId)
END
FROM dbo.PageHierarchy WHERE ParentPageId=#PageId
FOR XML PATH('Page'), TYPE)
END
and the SQL that calls the UDF
SELECT ModuleId AS "#ModuleId", PageId AS "#PageId",
ParentPageId AS "#ParentPageId", PageUrl AS "#PageUrl",
PageTitle AS "#PageTitle", PageOrder AS "#PageOrder",
dbo.PageHierarchyNode(PageId)
FROM PageHierarchy
FOR XML PATH('Page'), ROOT('SiteMap'), TYPE
this will nest the XML for me but it's duplicating nodes which is not what I want..
Edit 2:
I just needed to add a WHERE clause to the SELECT that calls the UDF:
...
WHERE ParentPageId IS NULL
Turns out I didn't want the CTE at all, just a UDF that I call recursively
CREATE FUNCTION PageHierarchyNode(#PageId int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN
(SELECT ModuleId AS "#ModuleId", PageId AS "#PageId",
ParentPageId AS "#ParentPageId", PageUrl AS "#PageUrl",
PageTitle AS "#PageTitle", PageOrder AS "#PageOrder",
CASE WHEN ParentPageId=#PageId
THEN dbo.PageHierarchyNode(PageId)
END
FROM dbo.PageHierarchy WHERE ParentPageId=#PageId
FOR XML PATH('Page'), TYPE)
END
with the SQL that calls the UDF as
SELECT ModuleId AS "#ModuleId", PageId AS "#PageId",
ParentPageId AS "#ParentPageId", PageUrl AS "#PageUrl",
PageTitle AS "#PageTitle", PageOrder AS "#PageOrder",
dbo.PageHierarchyNode(PageId)
FROM PageHierarchy
WHERE ParentPageId IS NULL
FOR XML PATH('Page'), ROOT('SiteMap'), TYPE
The question as well as the OP's answer helped me a lot. It took me a bit to grasp the answer as I was missing some context. So here's a seperate answer with a more generic explanation (I've tried to remove every bit of code that didn't relate directly to getting hierarchical data in XML output).
Suppose the following typical table for hierarchical data:
CREATE TABLE Employee (Id INT, BossId INT, Name NVARCHAR(50));
Suppose it has the following data:
INSERT INTO Employee (Id, BossId, Name) VALUES
(1, NULL, 'Boss Pancone'),
(2, 1, 'Capioregime Luciano'),
(3, 1, 'Capioregime Bruno'),
(4, 2, 'Johnny'),
(5, 2, 'Luca'),
(6, 2, 'Luciano jr.'),
(7, 3, 'Marco'),
(8, 3, 'Mario'),
(9, 3, 'Giacomo');
To get hierarchical XML data we could use the following function:
ALTER FUNCTION dbo.fn_EmployeeHierarchyNode (#BossId INT) RETURNS XML
BEGIN RETURN
(SELECT Id,
BossId,
Name,
dbo.fn_EmployeeHierarchyNode(Id)
FROM Employee
WHERE BossId = #BossId
FOR XML AUTO)
END;
Which can be called like this:
SELECT dbo.fn_EmployeeHierarchyNode(1)
Or, if you want the root node as well, like this:
SELECT Id,
BossId,
Name,
dbo.fn_EmployeeHierarchyNode(Id)
FROM Employee
WHERE BossId IS NULL
FOR XML AUTO
Which would produce:
<Employee Id="1" Name="Boss Pancone">
<Employee Id="2" BossId="1" Name="Capioregime Luciano">
<Employee Id="4" BossId="2" Name="Johnny" />
<Employee Id="5" BossId="2" Name="Luca" />
<Employee Id="6" BossId="2" Name="Luciano jr." />
</Employee>
<Employee Id="3" BossId="1" Name="Capioregime Bruno">
<Employee Id="7" BossId="3" Name="Marco" />
<Employee Id="8" BossId="3" Name="Mario" />
<Employee Id="9" BossId="3" Name="Giacomo" />
</Employee>
</Employee>
Recursive CTEs are not recursive as in "nested", they work differently and what you're trying to do doesn't work with CTEs. (Think of them as being always tail-recursive.)
The only way I have found to build recursive XML in SQL Server is by creating a scalar function which renders the nodes recursively; functions can make recursive calls so that this works as expected.

Resources