天天看點

vb.net 讀寫xml方法(1)(原創)

    Dim domXmlDocument As System.Xml.XmlDocument

    Dim tmpPath As String = AppTempFilePath

    Dim xmlFile As String = tmpPath + "/testXml.xml"

'窗體加載事件

    Private Sub TestXml_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        '讀xml過程測試通過

        Dim domXmlDocument As System.Xml.XmlDocument

        Dim tmpPath As String = AppTempFilePath

        Dim xmlFile As String = tmpPath + "/testXml.xml"

        Dim reader As System.Xml.XmlReader = Nothing

        Try

            reader = New Xml.XmlTextReader(xmlFile)

            'reader.

            While reader.Read

                Me.lboxXml.Items.Add(reader.Name + reader.Value)

            End While

        Catch ex As Exception

            MsgBox(ex.Message)

        Finally

            If Not (reader Is Nothing) Then

                reader.Close()

            End If

        End Try

    End Sub

    '載入xml事件

    Private Sub btnXmlLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXmlLoad.Click

        'Me.lboxXml.Items.Clear()

        ''讀xml過程測試通過

        'Dim reader As System.Xml.XmlReader = Nothing

        'Try

        '    reader = New Xml.XmlTextReader(xmlFile)

        '    While reader.Read

        '        Me.lboxXml.Items.Add(reader.Name + ":" + reader.Value)

        '    End While

        'Catch ex As Exception

        '    MsgBox(ex.Message)

        'Finally

        '    If Not (reader Is Nothing) Then

        '        reader.Close()

        '    End If

        'End Try

        Dim ds As New DataSet

        Try

            '如果直接使用ds做datasource則不會展開datagrid,用dv則可以直接顯示正确。

            ds.ReadXml(xmlFile)

            Dim tb As DataTable

            Dim dv As DataView

            tb = ds.Tables(0)

            dv = New DataView(tb)

            DataGrid1.DataSource = dv

            'DataGrid1.DataMember = "testXmlMember"

            'DataGrid1.DataMember = "employeefname"

            'Dim dxd As New XmlDataDocument

        Catch ex As Exception

            MsgBox(ex.Message.ToString)

        End Try

    End Sub

    '儲存建立xml内容事件

    Private Sub btnSaveNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveNew.Click

        Dim myTW As New XmlTextWriter(tmpPath + "/testXmlWrite.xml", Nothing)

        myTW.WriteStartDocument()

        myTW.Formatting = Formatting.Indented

        myTW.WriteStartElement("Team")

        myTW.WriteStartElement("player")

        myTW.WriteAttributeString("Name", "George Zip")

        myTW.WriteAttributeString("Position", "QB")

        myTW.WriteElementString("Nickname", "Zippy")

        myTW.WriteElementString("JerseyNumber", XmlConvert.ToString(7))

        myTW.WriteEndElement()

        myTW.WriteEndElement()

        myTW.WriteEndDocument()

        myTW.Close()

    End Sub

對于修改datagrid中指定内容并儲存到xml中還不會,弄明白了,在vb.net與xml讀寫的2中寫出來!