[英]Can't read xml nodes
I've the following XML
saved into settings.config
: 我将以下
XML
保存到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
: 这是我的反序列化
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
. 问题是
settings
变量返回Count = 0
。 What am I doing wrong? 我究竟做错了什么?
A few issues with your XML XML的一些问题
<Settings>
is your Root, it is not an element of your root. <Settings>
是您的根,不是您根的元素。 If you want to have multiple <Settings>
, then make a new root element, and put the <Settings>
tags inside that. <Settings>
,则创建一个新的根元素,并将<Settings>
标记放入其中。 Type
, Module
, and Capacity
are Elements, not Attributes Type
, Module
和Capacity
是元素,而不是属性 If you only have 1 settings note, you can do something like the following: 如果只有1个设置注释,则可以执行以下操作:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.