无法读取xml节点

时间:2016-05-05 14:36:50

标签: c# xml

我已将以下XML保存到settings.config

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Settings>
  <Type>15</Type>
  <Module>True</Module>
  <Capacity>10</Capacity>
</Settings>

我创建了一个这样的类:

 public class Settings
 {
      public int Type { get; set; }
      public bool Module { get; set; }
      public int Capacity { get; set; }
 }

这是我的代码,用于反序列化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();

问题是settings变量返回Count = 0。我究竟做错了什么?

3 个答案:

答案 0 :(得分:4)

XML的一些问题

  1. <Settings>是您的Root,它不是您的root的元素。如果您想要多个<Settings>,请创建一个新的根元素,并将<Settings>标记放在其中。
  2. TypeModuleCapacity是元素,而不是属性
  3. 如果您只有1个设置备注,则可以执行以下操作:

    var settignsNode = doc.Element("Settings");
    
    var settings = new Settings()
    {
        Type = (int)settignsNode.Element("Type"),
        // ...
    };
    

答案 1 :(得分:0)

工作示例,但上面的回答真的可以解释这里发生了什么

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

答案 2 :(得分:0)

工作代码

{ "Code": 200, 
"Errors": [], 
"GUID": "00000000-0000-0000-0000-000000000000", 
"IsSuccessful": true, 
"Message": null, 
"Result": { 
"AccessToken": "gAAAACDf3PAniQx1BqJ8qKZVlTQEP7JpvOYglvk8dsBV80mWxtmRCHc1CouejnKbsXEgYbOLXjN7rdZo-Bz535wdulxgkxRTmnEBTSgdZo-DkBHrp-HeiwjlBt_uSIhH7IdIr5dU0w4M_6KgUBI5e1_GWClDHvZY8R5GQahkpy24TGAp9AAAAIAAAAA11W-Eg", 
"AccessTokenExpirationUtc": "/Date(1445616318650)/", 
"AccessTokenIssueDateUtc": "/Date(1445612718666)/", 
"Callback": null, 
"RefreshToken": null, 
"Scope": [ "APIUSER" ] } }