Linq到XML文件查询不起作用
本文关键字:查询 不起作用 文件 XML Linq | 更新日期: 2023-09-27 18:21:22
这是我的XML文件,我正在使用linq和实体框架
<?xml version="1.0" encoding="utf-8" ?>
<Projects>
<Project ProjectId="JP001" Country="Canada" ProposedBy="Jim Priac"/>
<Project ProjectId="KS12" Country="Canada" ProposedBy="Aya Suriour"/>
<Project ProjectId="ANS16" Country="Malesia" ProposedBy="Gour martin"/>
<Projects>
我使用的linq查询是
IEnumerable<string> Proposed_By = from project in xmldoc.Descendants("Projects").Elements("Project")
where project.Attribute("Country") == "Canada"
select project.Attribute("ProposedBy");
但我没有得到正确的输出
您需要与属性的值进行比较,而不是与属性本身进行比较。
IEnumerable<string> Proposed_By =
from project in xmldoc.Descendants("Projects").Elements("Project")
where project.Attribute("Country").Value == "Canada"
select project.Attribute("ProposedBy").Value;
然而,我会更进一步,还检查属性是否存在(因为在null
对象上调用Value
属性会导致异常:
IEnumerable<string> Proposed_By =
from project in xmldoc.Descendants("Projects").Elements("Project")
where project.Attribute("Country") != null
& project.Attribute("Country").Value == "Canada"
& project.Attribute("ProposedBy") != null
select project.Attribute("ProposedBy").Value;
首先查看您的文件是否对linq查询进行更正
XDocument xmldoc = XDocument.Load(Path.GetFullPath("filename"));
IEnumerable<string> Proposed_By = from project in xmldoc.Descendants("Projects").Elements("Project")
where project.Attribute("Country").Value == "Canada"
select project.Attribute("ProposedBy").Value;
使用属性名为的.Value
另一种方式:如果Value不存在,则返回NULL。
var Propposed_By = from project in xd.Descendants("Projects").Elements("Project")
where project.Attribute("Country").Value == "Canada"
select (string)project.Attribute("ProposedBy");