将Sql表转换为XML

时间:2013-08-21 09:06:54

标签: xml sql-server-2008

我有一个表有三列的用户:Id,用户名,电子邮件。

我需要按以下格式将其转换为XML:

 <Table Name="Users">
      <Column Name='Id'>1</Column>
      <Column Name='Username'>user1</Column>
      <Column Name='Email'>user1@gmail.com</Column>
 </Table>
 <Table Name="Users">
      <Column Name='Id'>2</Column>
      <Column Name='Username'>user2</Column>
      <Column Name='Email'>user2@gmail.com</Column>
 </Table>

到现在为止,我写了这个:

select * from Users for xml raw('Table'), Elements, type

给了我这个结果:

 <Table>
      <Id>1</Id>
      <Username>user1</Username>
      <Email>user1@gmail.com</Email>
 </Table>
 <Table>
      <Id>2</Id>
      <Username>user2</Username>
      <Email>user2@gmail.com</Email>
 </Table>

2 个答案:

答案 0 :(得分:2)

select 'Users' as [@Name],
        (select 'Id'       as [@Name], Id       as '*' for xml path('Column'), type),
        (select 'Username' as [@Name], Username as '*' for xml path('Column'), type),
        (select 'Email'    as [@Name], Email    as '*' for xml path('Column'), type)
from Users
for xml path('Table'), type

SQL Fiddle

答案 1 :(得分:1)

不确定xsl解决方案是否合适。如果是以下将起作用:

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" encoding="utf-8" indent="yes" />

    <xsl:template match="AllUsers">
        <xsl:apply-templates select="Table" />
    </xsl:template>

    <xsl:template match="Table">
        <xsl:element name="{name()}">
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="*">
        <Column>
            <xsl:attribute name="Name">     
                <xsl:value-of select="name(.)" /> 
            </xsl:attribute>
            <xsl:value-of select="." />
        </Column>

    </xsl:template>

</xsl:stylesheet>

注意,AllUsers是源xml的根节点。