让我们假设一个名为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:26:55
你可以像下面这样写一个扩展方法:
public static class XMLExtension
{
public static string GetValue(this XElement input)
{
if (input != null)
return input.Value;
return null;
}
public static bool XMLContains(this string input, string value)
{
if (string.IsNullOrEmpty(input))
return false;
return input.Contains(value);
}
}并按如下方式使用:
IEnumerable<ProductRecord> results = from obj in DOC.Descendants("record")
where
obj.Element("id").GetValue().XMLContains(valueToSearch) || ...发布于 2010-11-07 21:20:54
您将获得一个NullReferenceException,因为您正在尝试访问某些节点的值,这些节点对于每个record都不存在,比如specs。在对其调用.Value之前,需要检查是否为obj.Element("specs") != null。
作为替代,您可以使用XPath:
var doc = XDocument.Load("test.xml");
var records = doc.XPathSelectElements("//record[contains(id, '2') or contains(name, 'test') or contains(resume, 'res') or contains(specs, 'spe')]");发布于 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
复制相似问题