我想將 SQL 資料庫中的資料寫入 XML 檔案。我知道可以使用資料集,但我不想使用它,因為我想用 XmlTextWriter 格式化我自己的 XML 檔案。
我會給你一些參考。
使用我的連接字串(名稱、密碼...),您可以構建一個新的 SqlConnection。然后我在我的 SQL 查詢所在的位置構建一個字串。然后我打開連接,它作業正常。但我的問題是,我不知道如何在我的 XML 檔案中寫入查詢的值。
connection = New SqlConnection(connetionString)
SQL查詢
Dim city As String = "SELECT City FROM info WHERE No = '1'"
編碼我如何構建我的 XML 檔案。
Dim xmlfile As String = "path name"
If IO.File.Exists(xmlfile) = True Then
IO.File.Delete(xmlfile)
End If
Dim enc As New System.Text.UTF8Encoding
Dim XMLbg As New Xml.XmlTextWriter(xmlfile, enc)
With XMLbg
.Formatting = Xml.Formatting.Indented
.Indentation = 4
.WriteStartDocument()
.WriteStartElement("Data")
--------------------------------------------------------
.WriteElementString("City", **'here must be the Data for the City'** )
.WriteEndElement() 'Data
'--------------------------------------------------------
XMLbg.Close()
End With
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Exception ", MessageBoxButtons.OK, MessageBoxIcon.Error)
也許有人知道該怎么做。謝謝 :)
uj5u.com熱心網友回復:
考慮使用物體框架。沒有資料集,沒有代碼上的 SQL。
uj5u.com熱心網友回復:
好吧,沒有資料集,只有資料表。
我不起來的XML格式,所以我不知道,如果For Each內部或外部的所屬WriteStartElement...WriteEndElement。我相信你知道它是如何作業的。
Private Sub WriteXMLFile()
Dim dt = GetDataForXMLFile()
Dim xmlfile As String = "path name"
If IO.File.Exists(xmlfile) = True Then
IO.File.Delete(xmlfile)
End If
Dim enc As New System.Text.UTF8Encoding
Dim XMLbg As New Xml.XmlTextWriter(xmlfile, enc)
With XMLbg
.Formatting = Xml.Formatting.Indented
.Indentation = 4
.WriteStartDocument()
For Each row As DataRow In dt.Rows
.WriteStartElement("Data")
.WriteElementString("City", Convert.ToString(row(0)))
.WriteEndElement() 'Data
Next
XMLbg.Close()
End With
End Sub
Private connectionString As String = "Your connection string"
Private Function GetDataForXMLFile() As DataTable
Dim dt As New DataTable
Dim city As String = "SELECT City FROM info WHERE No = '1'"
Using connection As New SqlConnection(connectionString),
cmd As New SqlCommand(city, connection)
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368122.html
