Maui-sHow to save and read data to/from XML ?

Dani_S 4,501 Reputation points
2023-10-15T15:37:56.3+00:00

Hi,

How to save and read data to/from XML ?

Thanks,

Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-10-16T02:03:21.6133333+00:00

    Hello,

    You can use do this by XmlSerializer. XmlSerializer could Write/read XML files element by element.

    For example, you can create an object called User.cs, you can add other properties as well.

    public class User
    {
         public string Name { get; set; }   
    }
    

    Then create a List and add new User object like following code.

    var users= new List<User>
    {
          new User { Name = "Test1" },
          new User { Name = "Test2" }
    };
    

    You can save these objects to local XML file.

    string filepath = @"c:\temp\users.xml";
    
    using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate))
    {
         XmlSerializer serializer = new XmlSerializer(users.GetType());
         serializer.Serialize(fs, users);
    }
    
    

    And you can read all of them from XML file.

    var getUsers = new List<User>();
    using (FileStream fs2 = new FileStream(filepath, FileMode.Open))
    {
         XmlSerializer serializer = new XmlSerializer(getUsers.GetType());
         getUsers  = serializer.Deserialize(fs2) as List<User>;
    }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.