【问题标题】:How to read data from SQL database and store it into an XML file?如何从 SQL 数据库中读取数据并将其存储到 XML 文件中?
【发布时间】:2010-04-15 10:11:56
【问题描述】:

我有一个 Silverlight 应用程序,它从 XML 文件中读取其内容。
用户可以输入数据并将其存储在 SQL 数据库中。

如何从 SQL 数据库中读取数据并将其存储到 XML 文件中?

【问题讨论】:

    标签: sql xml


    【解决方案1】:

    一种简单的方法(假设您使用的是 SQL Server)是在检索数据的查询末尾附加 FOR XML AUTO。然后将结果集作为 XML 文件返回。例如,以 Northwind 数据库为例,您可以使用以下查询:

    SELECT * FROM Products as P 
    INNER JOIN Categories as C 
    ON P.CategoryID = C.CategoryID 
    FOR XML AUTO
    

    这将生成以下 XML:

    <P ProductID="1" ProductName="Chai" SupplierID="1" CategoryID="1" QuantityPerUnit="10 boxes x 20 bags" UnitPrice="18.0000" UnitsInStock="39" UnitsOnOrder="0" ReorderLevel="10" Discontinued="0">
      <C CategoryID="1" CategoryName="Beverages" Description="Soft drinks, coffees, teas, beers, and ales" />
    </P>
    <P ProductID="2" ProductName="Chang" SupplierID="1" CategoryID="1" QuantityPerUnit="24 - 12 oz bottles" UnitPrice="19.0000" UnitsInStock="17" UnitsOnOrder="40" ReorderLevel="25" Discontinued="0">
      <C CategoryID="1" CategoryName="Beverages" Description="Soft drinks, coffees, teas, beers, and ales" />
    </P>
    

    更多信息请参见Retrieving Data as XML from SQL Server

    要从 SQL Server 检索数据,您需要使用 ADO.NET。这个话题太大了,这里就不细说了,建议reading a tutorial。但是,基本前提是您查询数据库并将数据作为 XML 返回,然后将其存储在字符串中。输入字符串后,您可以write this to a file

    【讨论】:

    • 谢谢丹,这很有帮助!但是我在哪里可以指定这些 XML 值将写入的文件的名称?
    • 您需要通过查询数据库以编程方式执行此操作,在 C# 中返回 XML,然后将其写入文件。有关更多信息,请参阅我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2018-12-01
    • 2013-10-14
    相关资源
    最近更新 更多