baltermia
baltermia

Reputation: 1343

How can I read an XML File and put the info in objects?

I have a function which writes all the Information of objects I have in a list into a XML file.

    public static void UpdateXML()
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        XmlWriter Writer = XmlWriter.Create("path", settings);
        Writer.WriteStartDocument();
        Writer.WriteStartElement("Accounts");
        foreach (var acc in Bank.Bankaccountlist)
        {
            Writer.WriteStartElement("Account");
            Writer.WriteAttributeString("ID", acc.id.ToString());
            Writer.WriteElementString("Name", acc.GetName());
            Writer.WriteElementString("Lastname", acc.GetLastname());
            Writer.WriteElementString("Balance", acc.GetBalance().ToString());
            Writer.WriteEndElement();
        }
        Writer.WriteEndElement();
        Writer.Flush();
        Writer.Close();
    }

Now, when the Program gets closed, all the Data is still in the file. So as soon as the Program starts again, it should create all the old objects again (creating an Account object will automatically put it in the list).

Could anyone tell me how that'd be possible?

Note that int id and double balance.

Upvotes: 0

Views: 74

Answers (3)

baltermia
baltermia

Reputation: 1343

I've come to following solution:

public static void ReadXML()
{
    DataSet xmlData = new DataSet();
    xmlData.ReadXml("path");

    foreach (DataTable table in xmlData.Tables)
    {
        foreach (DataColumn column in table.Columns)
        {
            foreach (DataRow row in table.Rows)
            {
                Account newAcc = new Account(row.ItemArray[0].ToString(), row.ItemArray[1].ToString(), Convert.ToDouble(row.ItemArray[2]), Convert.ToInt32(row.ItemArray[3]));
            }
        break;
        }
    }
}

This can 100% be improved, but it's works.

Upvotes: 1

jnkarate
jnkarate

Reputation: 46

You would also have to mark each part of the o jet as an xml attribute in order to serialize the object to xml. Then you can loop through the files in the xml directory and deserialize them, using the xml reader. I believe there is a nuget package to help with this.

Upvotes: 0

TinoZ
TinoZ

Reputation: 570

To give an answer depending on your actual solution, you should use a XmlReader as counterpart of your XmlWriter. For every property type other than string you should use Convert or the appropriate TryParse method. But you may have a look at the XmlSerializer which targets exactly your usecase.

https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer?view=netcore-3.1

Upvotes: 0

Related Questions