IlDrugo
IlDrugo

Reputation: 2069

Can't read xml nodes

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

Answers (3)

A few issues with your XML

  1. <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.
  2. Type, Module, and Capacity are Elements, not Attributes

If 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

BWA
BWA

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

layonez
layonez

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

Related Questions