我正在解析像这样的XElement对象
XElement teachers = new XElement("Teachers",
new XElement("Teacher1",
new XAttribute("Age", 27)),
new XElement("Teacher2",
new XAttribute("Age", 60)),
new XElement("Teacher3"),
new XAttribute("Age", 50));
使用此代码:
IEnumerable<string> oldTeachers = from teacher in teachers.Elements()
where int.Parse(teacher.Attribute("Age").Value) > 40
orderby teacher.Name.ToString() ascending
select teacher.Name.ToString();
但是我得到一个运行时错误,说&#34;对象引用未设置为where行上的对象实例。 我做错了什么?
编辑:
我发现问题是XElement声明:正确的声明应该是:
XElement teachers = new XElement("Teachers",
new XElement("Teacher1",
new XAttribute("Age", 27)),
new XElement("Teacher2",
new XAttribute("Age", 60)),
new XElement("Teacher3",
new XAttribute("Age", 50)));
答案 0 :(得分:1)
您始终可以使用XElement.ToString()
打印由代码构建的XML,第一个代码将Age="50"
属性添加到<Teachers>
节点:
<Teachers Age="50">
<Teacher1 Age="27" />
<Teacher2 Age="60" />
<Teacher3 />
</Teachers>
第二个代码正确地将属性添加到<Teacher3>
节点:
<Teachers>
<Teacher1 Age="27" />
<Teacher2 Age="60" />
<Teacher3 Age="50" />
</Teachers>
为了说清楚,我使用这个简单的行获得了XML:
Console.WriteLine(teachers);
//or more verbose :
//Console.WriteLine(teachers.ToString());
仅供参考,您可以通过将XAttribute
转换为int?
来避免此类异常(但在这种情况下,获取异常似乎更能让您意识到XElement
构造中存在错误:
IEnumerable<string> oldTeachers = from teacher in teachers.Elements()
where (int?)teacher.Attribute("Age") > 40
orderby teacher.Name.ToString() ascending
select teacher.Name.ToString();
答案 1 :(得分:0)
首先,您不应该通过元素的名称建立身份。元素的名称应该是它所代表的概念的名称。通过命名您的元素Teacher1
,Teacher2
和Teacher3
,您的处理难度超出预期。如果您需要身份,请向您的老师添加属性。
var teachers = new XElement("Teachers",
new XElement("Teacher",
new XAttribute("Id", 1),
new XAttribute("Age", 27)
),
new XElement("Teacher",
new XAttribute("Id", 2),
new XAttribute("Age", 60)
),
new XElement("Teacher",
new XAttribute("Id", 3),
new XAttribute("Age", 50)
)
);
在LINQ to XML中,如果需要Attribute / Element的值,则应该转换为适当的类型。
var oldTeachers =
from teacher in teachers.Elements("Teacher")
where (int)teacher.Attribute("Age") > 40
orderby (int)teacher.Attribute("Id") ascending
select "Teacher" + (int)teacher.Attribute("Id"); // or simply return the Id