[英]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的一些问题
<Settings>
是您的根,不是您根的元素。 如果要具有多个<Settings>
,则创建一个新的根元素,并将<Settings>
标记放入其中。 Type
, Module
和Capacity
是元素,而不是属性 如果只有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.