如何使用“xml路径”从SQL Server 2008生成xml文件时,仅将xsi:nil =“true”添加到一个字段

时间:2013-04-29 15:31:08

标签: sql-server xml sql-server-2008 xml-nil

以下是我正在使用的代码:

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"。感谢

1 个答案:

答案 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
)