首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >xml to c#查询帮助

xml to c#查询帮助
EN

Stack Overflow用户
提问于 2010-11-07 20:56:49
回答 3查看 389关注 0票数 1

让我们假设一个名为data.xml的xml文件,其中包含以下内容:

代码语言:javascript
复制
<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、姓名、简历或规范)包含给定值的所有记录。我已经创建了这段代码

代码语言:javascript
复制
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没有简历。

提前感谢

EN

Stack Overflow用户

发布于 2010-11-07 21:27:25

首先,我很惊讶它没有崩溃,因为您没有使用Namespace。也许c#4.0已经绕过了这个?

不管怎样,试一试

代码语言:javascript
复制
obj.Descendants("id").Any() ? root.Element("id").Value : null

这就是:

代码语言:javascript
复制
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
};
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4117788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档