Reputation: 784
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
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
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