让我们假设一个名为data.xml的xml文件,其中包含以下内容:
<root>
<record>
<id>1</id>
<name>test 1</name>
<resume>this is the resume</resume>
<specs>these are the specs</specs>
</record>
<record>
<id>2</id>
<name>test 2</name>
<resume>this is the resume 2</resume>
</record>
<record>
<id>3</id>
<name>test 3</name>
<specs>these are the specs 3</specs>
</record>
</root>我需要搜索其中任何字段(id、姓名、简历或规范)包含给定值的所有记录。我已经创建了这段代码
XDocument DOC = XDocument.Load("data.xml");
IEnumerable<ProductRecord> results = from obj in DOC.Descendants("record")
where
obj.Element("id").Value.Contains(valueToSearch) ||
obj.Element("name").Value.Contains(valueToSearch) ||
obj.Element("resume").Value.Contains(valueToSearch) ||
obj.Element("specs").Value.Contains(valueToSearch)
select new ProductRecord {
ID = obj.Element("id").Value,
Name = obj.Element("name").Value,
Resume = obj.Element("resume").Value,
Specs = obj.Element("specs").Value
};此代码抛出NullReference错误,因为并非所有记录都包含所有字段。在定义要应用的条件之前,如何测试当前记录是否有给定的元素?例如。Record@ID=3没有简历。
提前感谢
发布于 2010-11-07 21:27:25
首先,我很惊讶它没有崩溃,因为您没有使用Namespace。也许c#4.0已经绕过了这个?
不管怎样,试一试
obj.Descendants("id").Any() ? root.Element("id").Value : null这就是:
select new ProductRecord {
ID = obj.Descendants("id").Any() ? root.Element("id").Value : null,
Name = obj.Descendants("name").Any() ? root.Element("name").Value : null,
Resume = obj.Descendants("resume").Any() ? root.Element("resume").Value : null
Specs = obj.Descendants("specs").Any() ? root.Element("specs").Value : null
};https://stackoverflow.com/questions/4117788
复制相似问题