簡體   English   中英

無法讀取xml節點

[英]Can't read xml nodes

我將以下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 我究竟做錯了什么?

XML的一些問題

  1. <Settings>是您的根,不是您根的元素。 如果要具有多個<Settings> ,則創建一個新的根元素,並將<Settings>標記放入其中。
  2. TypeModuleCapacity是元素,而不是屬性

如果只有1個設置注釋,則可以執行以下操作:

var settignsNode = doc.Element("Settings");

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

工作示例,但是上面的答案實際上是在解釋這里的情況

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

工作代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM