2020年6月9日 星期二

vb.net 讀寫 XML [Read Write XML]


1
2
Imports System
Imports System.Xml





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'first let's check if there is a file MyXML.xml into our application folder
  'if there wasn't a file something like that, then let's create a new one.

  If IO.File.Exists("MyXML.xml") = False Then
   
   'declare our xmlwritersettings object
   Dim settings As New XmlWriterSettings()

   'lets tell to our xmlwritersettings that it must use indention for our xml
   settings.Indent = True

   'lets create the MyXML.xml document, the first parameter was the Path/filename of xml file
   ' the second parameter was our xml settings
   Dim XmlWrt As XmlWriter = XmlWriter.Create("MyXML.xml", settings)

   With XmlWrt

    ' Write the Xml declaration.
    .WriteStartDocument()

    ' Write a comment.
    .WriteComment("XML Database.")

    ' Write the root element.
    .WriteStartElement("Data")

    ' Start our first person.
    .WriteStartElement("Person")

    ' The person nodes.

    .WriteStartElement("FirstName")
    .WriteString("Alleo")
    .WriteEndElement()

    .WriteStartElement("LastName")
    .WriteString("Indong")
    .WriteEndElement()


    ' The end of this person.
    .WriteEndElement()

    ' Close the XmlTextWriter.
    .WriteEndDocument()
    .Close()

   End With

   MessageBox.Show("XML file saved.")
  End If
    End Sub


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'check if file myxml.xml is existing
  If (IO.File.Exists("MyXML.xml")) Then

   'create a new xmltextreader object
   'this is the object that we will loop and will be used to read the xml file
   Dim document As XmlReader = New XmlTextReader("MyXML.xml")

   'loop through the xml file
   While (document.Read())

    Dim type = document.NodeType

    'if node type was element
    If (type = XmlNodeType.Element) Then

     'if the loop found a <FirstName> tag
     If (document.Name = "FirstName") Then

      TextBox1.Text = document.ReadInnerXml.ToString()

     End If

     'if the loop found a <LastName tag
     If (document.Name = "LastName") Then

      TextBox2.Text = document.ReadInnerXml.ToString()

     End If

    End If

   End While

  Else

   MessageBox.Show("The filename you selected was not found.")
  End If
    End Sub

沒有留言:

張貼留言