vb.net 读写xml方法(1)

类别:.NET开发 点击:0 评论:0 推荐:

    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中写出来!

本文地址:http://com.8s8s.com/it/it41272.htm