使用完美的XML结构从SQL查询生成XML

时间:2018-11-30 05:43:10

标签: sql .net xml

我的SQl“员工”表看起来像

+-------+---------+--------+----------+
| Empid | Empname | Salary | Location |
+-------+---------+--------+----------+
|     1 | Arul    |    100 | Chennai  |
+-------+---------+--------+----------+

从SQl查询生成XML:

select * from employee for xml path, root('root')

从此Sql查询中,我正在获取如下所示的XML文件

<root>
  <employee>
    <Empid>1</Empid>
    <Empname>Arul</Empname>
    <Salary>100</Salary>
    <Location>Chennai</Location>
  </employee>
</root>

但是我期望SQL查询的XML输出为

<root>
<column>Empid</column>
<value>1</value>
<column>Empname</column>
<value>Arul</value>
</root>

1 个答案:

答案 0 :(得分:2)

正如您已经被告知的那样,所需的输出格式确实很糟糕而且很错误。不过,这可以很容易地完成:

DECLARE @mockup TABLE(Empid INT,Empname VARCHAR(100),Salary DECIMAL(10,4),[Location] VARCHAR(100));
INSERT INTO @mockup VALUES(1,'Arul',100,'Chennai')
                         ,(2,'One',200,'More');

SELECT 'Empid' AS [Column]
      ,EmpId AS [Value]
      ,'Empname' AS [Column]
      ,Empname AS [Value]
      -- follow this pattern...
FROM @mockup t
FOR XML PATH('employee'),ROOT('root');

结果

<root>
  <employee>
    <Column>Empid</Column>
    <Value>1</Value>
    <Column>Empname</Column>
    <Value>Arul</Value>
  </employee>
  <employee>
    <Column>Empid</Column>
    <Value>2</Value>
    <Column>Empname</Column>
    <Value>One</Value>
  </employee>
</root>                    

但是-碰巧-您应该尝试更改此格式。这真让人难以置信,肯定会令您头疼。

一些更好的建议:

<Employee>
  <Column name="EmpId" value="1" />
  <Column name="Empname" value="Arul" />
</Employee>

<employee id="1" name="Arul" />

<employee>
  <Id>1</Id>
  <Name>Arul</Name>
</employee>

或者(如果您真的想要坚持下去),至少要像这里的列索引

<root>
  <employee>
    <Column inx="1">Empid</Column>
    <Value inx="1">1</Value>
    <Column inx="2">Empname</Column>
    <Value inx="2">Arul</Value>
  </employee>
  <employee>
    <Column inx="1">Empid</Column>
    <Value inx="1">2</Value>
    <Column inx="2">Empname</Column>
    <Value inx="2">One</Value>
  </employee>
</root>                    

最后一个查询是这个

SELECT 1 AS [Column/@inx]
      ,'Empid' AS [Column]
      ,1 AS [Value/@inx]
      ,EmpId AS [Value]
      ,2 AS [Column/@inx]
      ,'Empname' AS [Column]
      ,2 AS [Value/@inx]
      ,Empname AS [Value]
      -- follow this pattern...
FROM @mockup t
FOR XML PATH('employee'),ROOT('root');