writting to xml

 

http://social.msdn.microsoft.com/Forums/zh-CN/vbgeneral/thread/06744366-c956-4e92-ace5-cd1fd5944232

 

Okay so say I have this XML:

How could I write to that, like add another game to it? Like rewrite that but from textboxes but create a whole new game after that game.

<Gamelist>



<Game>



<Name>



Oblivion 


</Name>



<Gamename>



Oblivion



</Gamename>



<Author>



Mocha



</Author>

<ID>



1

</ID>
</Game>
Code to append node using System.XML. Dont forget to import system.xml.
  • Can be further improved using LINQ to XML.

     

    Imports System.Xml
    
    Public Class Form1
    
      Private Sub UpdateXML()
        'You should take values as arguments
        'arguments such as FileName, if possible node to append to
        'and nodelist that is to appended
    
    
        'Fetch document to be processed
        Dim GameList As XmlDocument = New XmlDocument()
        GameList.Load("GameList.xml")
    
        'This will give you <Gamelist> node in mainNode object
        Dim mainNode As XmlNode = GameList.DocumentElement
    
        'Node to be appended
        Dim Game As XmlNode = GameList.CreateElement("Game")
    
        'subNode object can be used multiple times
    
        'declare a subNode
        'assign value
        'append it to Game node
        'reuse same object
        Dim subNode As XmlNode = GameList.CreateElement("Name")
        subNode.InnerText = TextBox1.Text 'Replace this
        Game.AppendChild(subNode)
    
        'As I said, use it for all the subnodes
        'you wish to append to <Game>
        subNode = GameList.CreateElement("Gamename")
        'subNode.InnerText = some other textbox.text
        Game.AppendChild(subNode)
    
        subNode = GameList.CreateElement("Author")
        'subNode.InnerText = some other textbox.text
        Game.AppendChild(subNode)
    
        subNode = GameList.CreateElement("Id")
        'subNode.InnerText = some other textbox.text
        Game.AppendChild(subNode)
    
        'Done adding subNodes to <Game>
    
        'Finally append <Game> to <Gamelist>
        mainNode.AppendChild(Game)
    
        'Save
        GameList.Save("C:\newGameList1.xml")
    
      End Sub
    
    
    End Class



    Thanks

  • The method I like is Serialization. You basically create a serializable class with the properties and/or methods you need on your object. Then you can serialize (save it to xml) or desierialize it (create it from xml) and you don’t have to worry about the xml.

    So a serializeable class of person might look like this:

    <Serializable()> _
    Public Class Person
      Private _Name As String
      <XmlElement()> _
      Public Property Name() As String
        Get
          Return _Name
        End Get
        Set(ByVal value As String)
          _Name = value
        End Set
      End Property
    
      Private _Gender As String
      <XmlElement()> _
      Public Property Gender() As String
        Get
          Return _Gender
        End Get
        Set(ByVal value As String)
          _Gender = value
        End Set
      End Property
    End Class
    

    In you app you would have a List(Of Person) to hold all of your people. When you Serialize it the xml will look like this:

    <?xml version="1.0" encoding="utf-16"?>
    <ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <Person>
      <Name>John</Name>
      <Gender>M</Gender>
     </Person>
     <Person>
      <Name>Jane</Name>
      <Gender>F</Gender>
     </Person>
     <Person>
      <Name>Jimmy</Name>
      <Gender>M</Gender>
     </Person>
     <Person>
      <Name>Jone</Name>
      <Gender>F</Gender>
     </Person>
     <Person>
      <Name>Frank</Name>
      <Gender>M</Gender>
     </Person>
    </ArrayOfPerson>
    

    If you add or remove any properties from your class the xml will automatically reflect the changes without you having to add the nodes to you function that loads or saves the xml.

    Below is an example to use it create a new app and paste all of the below code over the new From1’s code.

    Imports System.Xml
    Imports System.Xml.Serialization
    
    Public Class Form1
      Private xmlFileName As String = My.Computer.FileSystem.SpecialDirectories.Desktop + "\People.xml"
      Private People As New List(Of Person)
    
      Private Sub Add_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim newPerson As New Person
    
        'Create a new Person
        With newPerson
          .Name = InputBox("What name", "New Person")
          .Gender = InputBox("M/F", "New Person")
        End With
    
        'add to people list
        People.Add(newPerson)
    
        'update list databinding
        With lstPeople
          .DataSource = Nothing
          .DisplayMember = "Name"
          .DataSource = People
        End With
    
      End Sub
    
      Private Sub SavePeople()
        Dim xml_Writer As XmlWriter
    
        Dim xml_Serializer As XmlSerializer
    
        Try
          'Create a Serializer for your people list
          xml_Serializer = New XmlSerializer(GetType(List(Of Person)))
    
          'Create a xmlwriter to write to the xml file
          xml_Writer = New XmlTextWriter(xmlFileName, System.Text.Encoding.Unicode)
    
          'Serialize your list of people
          xml_Serializer.Serialize(xml_Writer, People)
        Catch ex As Exception
    
        Finally
          If xml_Writer IsNot Nothing Then
            If xml_Writer.WriteState <> WriteState.Closed Then
              xml_Writer.Close()
            End If
          End If
        End Try
      End Sub
    
      Private Sub LoadPeople()
        Dim xml_Reader As XmlReader
    
        Dim xml_Serializer As XmlSerializer
    
        Try
          xml_Serializer = New XmlSerializer(GetType(List(Of Person)))
    
          xml_Reader = New XmlTextReader(xmlFileName)
    
          People = CType(xml_Serializer.Deserialize(xml_Reader), List(Of Person))
        Catch ex As Exception
    
        Finally
          If xml_Reader IsNot Nothing Then
            If xml_Reader.ReadState <> ReadState.Closed Then
              xml_Reader.Close()
            End If
          End If
    
          'Create new list if the 
          'People.xml doesn't exist
          If People Is Nothing Then
            People = New List(Of Person)
          End If
        End Try
      End Sub
    
      Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        'Save your pep's
        SavePeople()
      End Sub
    
      Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'load your pep's
        LoadPeople()
    
        CreateControls()
      End Sub
    
      'Creates controls at runtime
      'for the example so you don't have to
      'at design time
      Private Sub CreateControls()
        lstPeople = New ListBox
    
        With lstPeople
          .DataSource = People
          .Dock = DockStyle.Top
    
          .DisplayMember = "Name"
        End With
    
        Me.Controls.Add(lstPeople)
    
        Dim newButton As New Button
    
        With newButton
          .Text = "Add"
          .Location = New Point(lstPeople.Right - .Width, lstPeople.Bottom + 5)
        End With
    
        AddHandler newButton.Click, AddressOf Add_Click
    
        Me.Controls.Add(newButton)
      End Sub
    
      Private lstPeople As ListBox
    End Class
    
    <Serializable()> _
    Public Class Person
      Private _Name As String
      <XmlElement()> _
      Public Property Name() As String
        Get
          Return _Name
        End Get
        Set(ByVal value As String)
          _Name = value
        End Set
      End Property
    
      Private _Gender As String
      <XmlElement()> _
      Public Property Gender() As String
        Get
          Return _Gender
        End Get
        Set(ByVal value As String)
          _Gender = value
        End Set
      End Property
    End Class  
  • Can be further improved using LINQ to XML.

     

    Imports System.Xml
    
    Public Class Form1
    
      Private Sub UpdateXML()
        'You should take values as arguments
        'arguments such as FileName, if possible node to append to
        'and nodelist that is to appended
    
    
        'Fetch document to be processed
        Dim GameList As XmlDocument = New XmlDocument()
        GameList.Load("GameList.xml")
    
        'This will give you <Gamelist> node in mainNode object
        Dim mainNode As XmlNode = GameList.DocumentElement
    
        'Node to be appended
        Dim Game As XmlNode = GameList.CreateElement("Game")
    
        'subNode object can be used multiple times
    
        'declare a subNode
        'assign value
        'append it to Game node
        'reuse same object
        Dim subNode As XmlNode = GameList.CreateElement("Name")
        subNode.InnerText = TextBox1.Text 'Replace this
        Game.AppendChild(subNode)
    
        'As I said, use it for all the subnodes
        'you wish to append to <Game>
        subNode = GameList.CreateElement("Gamename")
        'subNode.InnerText = some other textbox.text
        Game.AppendChild(subNode)
    
        subNode = GameList.CreateElement("Author")
        'subNode.InnerText = some other textbox.text
        Game.AppendChild(subNode)
    
        subNode = GameList.CreateElement("Id")
        'subNode.InnerText = some other textbox.text
        Game.AppendChild(subNode)
    
        'Done adding subNodes to <Game>
    
        'Finally append <Game> to <Gamelist>
        mainNode.AppendChild(Game)
    
        'Save
        GameList.Save("C:\newGameList1.xml")
    
      End Sub
    
    
    End Class



    Thanks

    The method I like is Serialization. You basically create a serializable class with the properties and/or methods you need on your object. Then you can serialize (save it to xml) or desierialize it (create it from xml) and you don’t have to worry about the xml.
  • So a serializeable class of person might look like this:

    <Serializable()> _
    Public Class Person
      Private _Name As String
      <XmlElement()> _
      Public Property Name() As String
        Get
          Return _Name
        End Get
        Set(ByVal value As String)
          _Name = value
        End Set
      End Property
    
      Private _Gender As String
      <XmlElement()> _
      Public Property Gender() As String
        Get
          Return _Gender
        End Get
        Set(ByVal value As String)
          _Gender = value
        End Set
      End Property
    End Class
    

    In you app you would have a List(Of Person) to hold all of your people. When you Serialize it the xml will look like this:

    <?xml version="1.0" encoding="utf-16"?>
    <ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <Person>
      <Name>John</Name>
      <Gender>M</Gender>
     </Person>
     <Person>
      <Name>Jane</Name>
      <Gender>F</Gender>
     </Person>
     <Person>
      <Name>Jimmy</Name>
      <Gender>M</Gender>
     </Person>
     <Person>
      <Name>Jone</Name>
      <Gender>F</Gender>
     </Person>
     <Person>
      <Name>Frank</Name>
      <Gender>M</Gender>
     </Person>
    </ArrayOfPerson>
    

    If you add or remove any properties from your class the xml will automatically reflect the changes without you having to add the nodes to you function that loads or saves the xml.

    Below is an example to use it create a new app and paste all of the below code over the new From1’s code.

    Imports System.Xml
    Imports System.Xml.Serialization
    
    Public Class Form1
      Private xmlFileName As String = My.Computer.FileSystem.SpecialDirectories.Desktop + "\People.xml"
      Private People As New List(Of Person)
    
      Private Sub Add_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim newPerson As New Person
    
        'Create a new Person
        With newPerson
          .Name = InputBox("What name", "New Person")
          .Gender = InputBox("M/F", "New Person")
        End With
    
        'add to people list
        People.Add(newPerson)
    
        'update list databinding
        With lstPeople
          .DataSource = Nothing
          .DisplayMember = "Name"
          .DataSource = People
        End With
    
      End Sub
    
      Private Sub SavePeople()
        Dim xml_Writer As XmlWriter
    
        Dim xml_Serializer As XmlSerializer
    
        Try
          'Create a Serializer for your people list
          xml_Serializer = New XmlSerializer(GetType(List(Of Person)))
    
          'Create a xmlwriter to write to the xml file
          xml_Writer = New XmlTextWriter(xmlFileName, System.Text.Encoding.Unicode)
    
          'Serialize your list of people
          xml_Serializer.Serialize(xml_Writer, People)
        Catch ex As Exception
    
        Finally
          If xml_Writer IsNot Nothing Then
            If xml_Writer.WriteState <> WriteState.Closed Then
              xml_Writer.Close()
            End If
          End If
        End Try
      End Sub
    
      Private Sub LoadPeople()
        Dim xml_Reader As XmlReader
    
        Dim xml_Serializer As XmlSerializer
    
        Try
          xml_Serializer = New XmlSerializer(GetType(List(Of Person)))
    
          xml_Reader = New XmlTextReader(xmlFileName)
    
          People = CType(xml_Serializer.Deserialize(xml_Reader), List(Of Person))
        Catch ex As Exception
    
        Finally
          If xml_Reader IsNot Nothing Then
            If xml_Reader.ReadState <> ReadState.Closed Then
              xml_Reader.Close()
            End If
          End If
    
          'Create new list if the 
          'People.xml doesn't exist
          If People Is Nothing Then
            People = New List(Of Person)
          End If
        End Try
      End Sub
    
      Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        'Save your pep's
        SavePeople()
      End Sub
    
      Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'load your pep's
        LoadPeople()
    
        CreateControls()
      End Sub
    
      'Creates controls at runtime
      'for the example so you don't have to
      'at design time
      Private Sub CreateControls()
        lstPeople = New ListBox
    
        With lstPeople
          .DataSource = People
          .Dock = DockStyle.Top
    
          .DisplayMember = "Name"
        End With
    
        Me.Controls.Add(lstPeople)
    
        Dim newButton As New Button
    
        With newButton
          .Text = "Add"
          .Location = New Point(lstPeople.Right - .Width, lstPeople.Bottom + 5)
        End With
    
        AddHandler newButton.Click, AddressOf Add_Click
    
        Me.Controls.Add(newButton)
      End Sub
    
      Private lstPeople As ListBox
    End Class
    
    <Serializable()> _
    Public Class Person
      Private _Name As String
      <XmlElement()> _
      Public Property Name() As String
        Get
          Return _Name
        End Get
        Set(ByVal value As String)
          _Name = value
        End Set
      End Property
    
      Private _Gender As String
      <XmlElement()> _
      Public Property Gender() As String
        Get
          Return _Gender
        End Get
        Set(ByVal value As String)
          _Gender = value
        End Set
      End Property
    End Class
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值