Reputation: 2069
I've the following XML
saved into settings.config
:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Settings>
<Type>15</Type>
<Module>True</Module>
<Capacity>10</Capacity>
</Settings>
I've created a class like this:
public class Settings
{
public int Type { get; set; }
public bool Module { get; set; }
public int Capacity { get; set; }
}
and this is my code that deserialize the XML
:
XDocument doc = XDocument.Load("settings.config");
var settings = doc.Root
.Elements("Settings")
.Select(x => new Settings
{
Type = (int)x.Attribute("Type"),
Module = (bool)x.Attribute("Module"),
Capacity = (int)x.Attribute("Capacity"),
})
.ToList();
The problem is that the settings
variable return Count = 0
. What am I doing wrong?
Upvotes: 0
Views: 100
Reputation: 31194
A few issues with your XML
<Settings>
is your Root, it is not an element of your root. If you want to have multiple <Settings>
, then make a new root element, and put the <Settings>
tags inside that.Type
, Module
, and Capacity
are Elements, not AttributesIf you only have 1 settings note, you can do something like the following:
var settignsNode = doc.Element("Settings");
var settings = new Settings()
{
Type = (int)settignsNode.Element("Type"),
// ...
};
Upvotes: 4
Reputation: 5764
Working code
XDocument doc = XDocument.Parse("<Settings><Type>15</Type><Module>True</Module><Capacity>10</Capacity></Settings>");
var settings = doc
.Elements("Settings")
.Select(x => new Settings
{
Type = (int)x.Element("Type"),
Module = (bool)x.Element("Module"),
Capacity = (int)x.Element("Capacity"),
})
.ToList();
Upvotes: 0
Reputation: 1785
Working example, but answer above is really explain what is going here
XDocument doc = XDocument.Parse("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><Settings><Type>15</Type><Module>True</Module><Capacity>10</Capacity></Settings>");
var settings = doc
.Elements("Settings")
.Select(x => new Settings
{
Type = (int.Parse(x.Elements("Type").First().Value)),
Module = bool.Parse(x.Elements("Module").First().Value),
Capacity = (int.Parse(x.Elements("Capacity").First().Value)),
})
.ToList();
Upvotes: 0