Here is the code I am using:
DECLARE @returnXML XML
SELECT @ReturnXML =
(SELECT [StudentID/SSN] = ssn,
[StudentName/LastName] = lastname,
[StudentName/FirstName] = firstname,
[StudentName/MiddleInitial] = Middlename,
[PrimaryAddress/Street1] = line1,
[PrimaryAddress/Street2] = line2,
[PrimaryAddress/City] = city,
[PrimaryAddress/State] = state,
[PrimaryAddress/Country] = ISNULL(country,null),
[PrimaryAddress/Zip] = zipcode
FROM StudentTable
FOR XML Path('Student'), ROOT('Root'),TYPE
)
SELECT @ReturnXML
FOR XML PATH('');
Only for the country node do I need to set xsi:nil="true". Thanks
Generating Elements for NULL Values Using the XSINIL Parameter
Add
ELEMENTS XSINIL
to theFOR XML
clause.The above will set
xsi:nil="true"
for all nodes in the XML that isNULL
.To do it only for one field you can use a subquery with
ELEMENTS XSINIL
to build the XML for that field.