【问题标题】:how to create XML file from database in vb.net如何在 vb.net 中从数据库创建 XML 文件
【发布时间】:2013-08-01 06:57:50
【问题描述】:

如何使用 vb.net 从数据库创建 XML 文件 当我尝试时,我只得到了创建的根元素,而不是数据库中的任何数据,我的代码是:

<% @Import Namespace="System" %>
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.xml" %>
<% @Import Namespace="System.Data.SqlClient" %>

<Script runat="server">
Sub Page_Load

Dim connectionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds  As New DataSet
Dim sql As String

connectionString =// my connection string///
connection = New SqlConnection(connectionString) 


sql = "select * from jb_jobs where city='Los Angeles' "
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
connection.Close()
If IO.File.Exists("product.xml") = False Then
Dim settings As New XmlWriterSettings()
settings.Indent = True
Dim XmlWrt As XmlWriter = XmlWriter.Create("c:/xmlfiles/product.xml", settings)
XmlWrt.WriteStartDocument()
XmlWrt.WriteComment("XML Database.")
XmlWrt.WriteStartElement("source")
XmlWrt.WriteStartElement("jobs")



XmlWrt.WriteEndElement()
XmlWrt.WriteEndDocument()
XmlWrt.Close()
End If
End Sub
</script>

我得到的输出只是一个 XML 文件,它只包含上述根元素,而不是来自数据库的数据。

如何从数据库中获取数据并形成 XML 文件?

【问题讨论】:

    标签: sql xml vb.net


    【解决方案1】:

    尝试使用 WriteXml 方法,如下所示:

    Private Sub WriteXmlToFile(thisDataSet As DataSet)
     If thisDataSet Is Nothing Then 
         Return 
     End If  
    
    ' Create a file name to write to. 
     Dim filename As String = "XmlDoc.xml" 
    
     ' Create the FileStream to write with. 
     Dim stream As New System.IO.FileStream _
        (filename, System.IO.FileMode.Create)
    
     ' Write to the file with the WriteXml method.
     thisDataSet.WriteXml(stream)
    End Sub
    

    您可以在 MSDN 上找到有关 DataTable.WriteXmlDataSet.WriteXml 的更多信息。

    【讨论】:

    • 我在创建 XML 文件时没有任何问题,但问题在于从数据库中检索值并将其保存到 XML 文件中
    【解决方案2】:

    所以你应该问过'从数据库中检索数据'??

    改变SQL语句怎么样:

    SQL = select * from jb_jobs where city='Los Angeles'

    SQL = select * from jb_jobs where city LIKE 'Los Angeles' -> 字符串

    SQL = select * from jb_jobs where city = CityID -> 整数

    【讨论】: