locked
Saving from Text Boxes to Xml file - System.InvalidOperationException RRS feed

  • Question

  • I have a windows form w/ 10 text boxes.  I found this VB code to update an Xml file with the text box contents.  I'm still trying to test/understand it but receive the following error:

    System.InvalidOperationException    {"There is an error in XML document (2, 2)."}

    for this line of code:

     

               'Deserialize the XML into our container object

                ExistingData = Serializer.Deserialize(OpenStream)

     

     

    Any help would be much appreciated.

    Regards.

     

    --------------- Complete section of code shown below --------------------------

     

     

        Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click

            'Create the ListOf(ListOf(String))

     

            'This is a simple container for a collection of strings that supports serialization

     

            Dim ExistingData As New List(Of List(Of String))

     

            'Create the XML serialization object

     

            Dim Serializer As New System.Xml.Serialization.XmlSerializer(GetType(List(Of List(Of String))))

     

            'If we already have a data file, load its contents so that previously saved data is not overwritten

     

            If System.IO.File.Exists(Application.StartupPath & "\sContacts.xml") Then

     

                'Create a FileStream to read the XML text file into

     

                Dim OpenStream As System.IO.FileStream = System.IO.File.Open(Application.StartupPath & "\sContacts.xml", IO.FileMode.Open)

     

                'Deserialize the XML into our container object

     

                ExistingData = Serializer.Deserialize(OpenStream)

     

                'Close the stream

     

                OpenStream.Close()

     

            End If

     

            'Now create a new ListOf(String) object to hold the new input data

     

            Dim NewData As New List(Of String)

     

            'Add the data to the new list

     

            NewData.Add(Sbox1.Text)

            NewData.Add(Sbox2.Text)

            NewData.Add(Sbox3.Text)

            NewData.Add(Sbox4.Text)

            NewData.Add(Sbox5.Text)

            NewData.Add(Sbox6.Text)

            NewData.Add(Sbox7.Text)

            NewData.Add(Sbox8.Text)

            NewData.Add(Sbox9.Text)

            NewData.Add(Sbox10.Text)

     

            'Add the new list to the existing string list container

     

            ExistingData.Add(NewData)

     

            'Save the updated container back to the XML file on disk

     

            'Create a file stream as we did above - note the create option rather than open

     

            Dim SaveStream As System.IO.FileStream = System.IO.File.Open(Application.StartupPath & "\sContacts.xml", IO.FileMode.Create)

     

            'Serialize the container object to XML

     

            Serializer.Serialize(SaveStream, ExistingData)

     

            'Close the stream

     

            SaveStream.Close()

     

            'Clear the text boxes to show that the save is complete and to allow a new entry

     

            'Sbox1.Clear()

     

        End Sub

     

    Tuesday, July 26, 2011 7:02 PM

Answers

  • Hi,

    Sorry, I used C# as I'm not familiar with VB.net

    <XmlRoot("user_list")> _
    Public Class UserList
      
      Public Sub New()
        MyBase.New
        Items = New List(Of User)
      End Sub
      
      <XmlElement("user")> _
      Public Property Items As List(Of User)
      End Property
    End Class
    Public Class User
      
      <XmlElement("id")> _
      Public Property Id As Int32
      End Property
      
      <XmlElement("name")> _
      Public Property Name As String
      End Property
    End Class
    Class Program
      
      Private Shared Sub Main()
        Dim open As FileStream = File.Open("d:/test.xml", FileMode.Open)
        Dim ser As XmlSerializer = New XmlSerializer(GetType(UserList))
        Dim test As var = ser.Deserialize(open)
        Dim list As UserList = New UserList
        'list.Items.Add(new User { Id = 1, Name = "abc" });
        'list.Items.Add(new User { Id = 2, Name = "def" });
        'list.Items.Add(new User { Id = 3, Name = "ghi" });
        'ser.Serialize(Console.Out, list);
      End Sub
    End Class
    

    I used this link to transform: http://www.carlosag.net/Tools/CodeTranslator/

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Saturday, July 30, 2011 2:13 PM
    Moderator

All replies

  • Hi,

    >>ExistingData = Serializer.Deserialize(OpenStream)

    you need to create a type to retrieve the collection, and you should use the xml's root name as class's name, I test it.

    BTW, I think you can use Linq to XML to retrive all nodes' values, it is a easy way to handle xml(add, delete, update,save).

    you can refer here: http://msdn.microsoft.com/en-us/library/bb387098.aspx

    http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, July 27, 2011 8:43 AM
    Moderator
  • Hi... thanks for the recommendation but I'm not sure how to:

    "create a type to retrieve the collection, and you should use the xml's root name as class's name" even after some additional research here.

    I'm new to a lot of this and any other help is appreciated.

    Regards,

    Wednesday, July 27, 2011 1:32 PM
  • Hi,

    Thanks for your feedback.

    Here is a sample code:

    [XmlRoot("user_list")]
      public class UserList
      {
        public UserList() { Items = new List<User>(); }
        [XmlElement("user")]
        public List<User> Items { get; set; }
      }
      public class User
      {
        [XmlElement("id")]
        public Int32 Id { get; set; }
    
        [XmlElement("name")]
        public String Name { get; set; }
      }
    
      static class Program
      {
        static void Main()
        {
          FileStream open = File.Open(@"d:/test.xml", FileMode.Open);
          XmlSerializer ser = new XmlSerializer(typeof(UserList));
          var test = ser.Deserialize(open);
          UserList list = new UserList();
          //list.Items.Add(new User { Id = 1, Name = "abc" });
          //list.Items.Add(new User { Id = 2, Name = "def" });
          //list.Items.Add(new User { Id = 3, Name = "ghi" });
          //ser.Serialize(Console.Out, list);
        }
      }
    

    --------------------------------------------

    XML:

    <?xml version="1.0"?>
    <user_list>
      <user>
       <id>1</id>
       <name>Joe</name>
      </user>
      <user>
       <id>2</id>
       <name>John</name>
      </user>
    </user_list>
    

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, July 28, 2011 5:30 AM
    Moderator
  • Hi... what language is this?  I'm coding in VB .net.
    Thursday, July 28, 2011 6:27 PM
  • Hi,

    Sorry, I used C# as I'm not familiar with VB.net

    <XmlRoot("user_list")> _
    Public Class UserList
      
      Public Sub New()
        MyBase.New
        Items = New List(Of User)
      End Sub
      
      <XmlElement("user")> _
      Public Property Items As List(Of User)
      End Property
    End Class
    Public Class User
      
      <XmlElement("id")> _
      Public Property Id As Int32
      End Property
      
      <XmlElement("name")> _
      Public Property Name As String
      End Property
    End Class
    Class Program
      
      Private Shared Sub Main()
        Dim open As FileStream = File.Open("d:/test.xml", FileMode.Open)
        Dim ser As XmlSerializer = New XmlSerializer(GetType(UserList))
        Dim test As var = ser.Deserialize(open)
        Dim list As UserList = New UserList
        'list.Items.Add(new User { Id = 1, Name = "abc" });
        'list.Items.Add(new User { Id = 2, Name = "def" });
        'list.Items.Add(new User { Id = 3, Name = "ghi" });
        'ser.Serialize(Console.Out, list);
      End Sub
    End Class
    

    I used this link to transform: http://www.carlosag.net/Tools/CodeTranslator/

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Saturday, July 30, 2011 2:13 PM
    Moderator
  • Hi,

    I am writing to check the status of the issue on your side.  Would you mind letting us know the result of the suggestions?

    If you need further assistance, please feel free to let me know.   I will be more than happy to be of assistance.

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, August 2, 2011 3:57 PM
    Moderator