简体   繁体   中英

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?

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"),
    // ...
};

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM