如何使sql查询结果到xml文件

时间:2013-09-06 09:14:42

标签: c# sql sql-server xml

我有一个SQL查询,从表中选择一些数据。

ID    Name    Number    Email
1      a        123       a@a.com
2      b        321       b@b.com
3      c        432       c@c.com

我从表中获取这些数据。我想从数据创建一个xml文件。喜欢这个

<Students>
  <Student>
      <id>1</id>
      <name>a</name>
      <number>123</number>
      <email>a@a.com</email>
  </Student>
  <Student>
      <id>2</id>
      <name>b</name>
      <number>321</number>
      <email>b@b.com</email>
  </Student>
  <Student>
      <id>3</id>
      <name>c</name>
      <number>432</number>
      <email>c@c.com</email>
  </Student>
</Students>

如何在C#和SQL Server上执行此操作?

3 个答案:

答案 0 :(得分:35)

试试这个:

SELECT *
FROM dbo.YourStudentTable
FOR XML PATH('Student'), ROOT ('Students')

这应该返回您正在寻找的XML(假设您有SQL Server 2005 或更新)

阅读more about how to use FOR XML PATH and its capabilities on TechNet

答案 1 :(得分:2)

1)创建名为student

的课程
[Serializable]
public class Student
{
  public int ID { get; set; }
  public string Name { get; set; }
  public int Number { get; set; }
  public string Email { get; set; }
}

2)从数据库

获取名为StudentList的List中的数据

3)然后打开或创建xml文件并添加值

using (XmlWriter writer = XmlWriter.Create("Student.xml"))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Students");

    foreach (Student student in StudentList)
    {
    writer.WriteStartElement("Student");

    writer.WriteElementString("id", student.ID.ToString());
    writer.WriteElementString("name", student.Name.ToString());
    writer.WriteElementString("number", student.Number.ToString());
    writer.WriteElementString("email", student.Email.ToString());

    writer.WriteEndElement();
    }

    writer.WriteEndElement();
    writer.WriteEndDocument();
}

答案 2 :(得分:1)

虽然marc提供的解决方案正是您所需要的,但您可能希望深入了解文章Using the FOR XML Clause to Return Query Results as XML中的各种选项。