xml auto或xml路径?

时间:2012-12-31 11:19:32

标签: c# asp.net sql xml

执行以下查询

SELECT     AssessmentFileGUID as '@FileId',AssessmentFileTypeId as '@FileTypeId',AssessmentFileName
FROM         rat.AssessmentFile where AssessmentId=17 
for xml path('File'),root('Files')

给了我以下结果:

<Files>
  <File FileId="2A23D836-612F-418E-BDE8-F182C5432A0D" FileTypeId="1">
    <AssessmentFileName>File-123213.pdf</AssessmentFileName>
  </File>
  <File FileId="CDA853B9-C587-4365-BAF5-972F8D217BAC" FileTypeId="2">
    <AssessmentFileName>File-343455.png</AssessmentFileName>
  </File>
</Files>

但是我需要采用以下格式:

<Files>
  <File FileId="2A23D836-612F-418E-BDE8-F182C5432A0D" FileTypeId="1">File-123213.pdf</File>
  <File FileId="CDA853B9-C587-4365-BAF5-972F8D217BAC" FileTypeId="2">File-343455.png</File>
</Files>

2 个答案:

答案 0 :(得分:2)

指定应作为data()内容的列,它应该放在正确的位置:

declare @T table (
    AssessmentFileGUID uniqueidentifier not null,
    AssessmentFileTypeId int not null,
    AssessmentFileName varchar(max) not null,
    AssessmentId int not null
)
insert into @T(AssessmentFileGUID,AssessmentFileTypeId,AssessmentFileName,
     AssessmentId) values
('2A23D836-612F-418E-BDE8-F182C5432A0D',1,'File-123213.pdf',17),
('CDA853B9-C587-4365-BAF5-972F8D217BAC',2,'File-343455.png',17)

SELECT     AssessmentFileGUID as '@FileId',AssessmentFileTypeId as '@FileTypeId',
     AssessmentFileName as 'data()' //Change here
FROM         @T where AssessmentId=17 
for xml path('File'),root('Files')

结果:

<Files>
    <File FileId="2A23D836-612F-418E-BDE8-F182C5432A0D" FileTypeId="1">File-123213.pdf</File>
    <File FileId="CDA853B9-C587-4365-BAF5-972F8D217BAC" FileTypeId="2">File-343455.png</File>
</Files>

答案 1 :(得分:1)

不确定但是试试这个

SELECT     
    AssessmentFileGUID as '@FileId',
    AssessmentFileTypeId as '@FileTypeId',
    AssessmentFileName as "File/text()"
FROM         
    rat.AssessmentFile 
where 
    AssessmentId = 17 
FOR XML PATH('File'), ROOT('Files')