以下是我正在使用的代码:
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('');
只有国家/地区节点才需要设置xsi:nil =" true"。感谢
答案 0 :(得分:1)
Generating Elements for NULL Values Using the XSINIL Parameter
将ELEMENTS XSINIL
添加到FOR 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] = country,
[PrimaryAddress/Zip] = zipcode
FROM StudentTable
FOR XML Path('Student'), ROOT('Root'), TYPE, ELEMENTS XSINIL
)
以上内容将为XML中xsi:nil="true"
的所有节点设置NULL
。
要仅对一个字段执行此操作,您可以使用带有ELEMENTS XSINIL
的子查询来为该字段构建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] = (SELECT Country = country FOR XML PATH(''), TYPE, ELEMENTS XSINIL),
[PrimaryAddress/Zip] = zipcode
FROM StudentTable
FOR XML Path('Student'), ROOT('Root'), TYPE
)