Giovanni Le Grand
Giovanni Le Grand

Reputation: 784

C#: help using XML and multiple accounts

i am messing around with some xml and c# but ran into a problem, i have an xml file called: application.login.xml containing:

<?xml version="1.0" encoding="utf-8" ?>
<account>

  <admin>
    <username>admin</username>
    <password>admin</password>
    <recht>admin</recht>
  </admin>

  <demo>
    <username>demo</username>
    <password>demo</password>
    <recht>user</recht>
  </demo>

</account>

but whenever i try to read this out into the class: account.cs i get the following messages: Could not find schema information for the element demo, admin etc.

the code i use to deserialize it is:

XmlSerializer xSer = new XmlSerializer(typeof(account));
Console.WriteLine(xSer.Deserialize(fs));

so how can i manage to store multiple accounts into 1 xml?

the content of the class account is:

namespace bedrijfManagement
{
    public class account
    {
         public string username, password, recht;
    }
}

Upvotes: 1

Views: 83

Answers (2)

j.kahil
j.kahil

Reputation: 286

you need to create new class named Accounts

public class Accounts 
{
    public List<Account> accounts{get;set;}

}

XmlSerializer xSer = new XmlSerializer(typeof(Accounts));
var result = (Accounts) xSer.Deserialize(fs);

and your file should be like

<accounts>   
<account>
        <username>admin</username>
        <password>admin</password>
        <recht>admin</recht>   
</account>  
 <account>
        <username>demo</username>
        <password>demo</password>
        <recht>user</recht>  
 </account> 
</accounts>

if you use

XmlSerializer xSer = new XmlSerializer(typeof(List<account>));

the xml file should be like this

<arrayofaccount>
<account>
    <username>admin</username>
    <password>admin</password>
    <recht>admin</recht>
  </account>
  <account>
    <username>demo</username>
    <password>demo</password>
    <recht>user</recht>
  </account>
</arrayofaccount>

Upvotes: 1

David
David

Reputation: 218960

I don't see any properties on the account class called admin or demo. It looks like you're missing a level of abstraction, both in the code and in the XML. Consider an XML structure like the following:

<accounts>
  <account>
    <username>admin</username>
    <password>admin</password>
    <recht>admin</recht>
  </account>
  <account>
    <username>demo</username>
    <password>demo</password>
    <recht>user</recht>
  </account>
</accounts>

That should be deserializable into a collection of account objects, since that's exactly what it is. In the code then you'd deserialize it into a collection, not a single instance:

XmlSerializer serializer = new XmlSerializer(typeof(List<account>));
List<account> accounts = serializer.Deserialize(xmlInput);

Upvotes: 0

Related Questions