This is my XML file and I am using linq and entity framework
<?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>
the linq query I am using is
IEnumerable<string> Proposed_By = from project in xmldoc.Descendants("Projects").Elements("Project")
where project.Attribute("Country") == "Canada"
select project.Attribute("ProposedBy");
but I am not getting correct output
You need to compare to the value of the attribute and not to the attribute itself.
IEnumerable<string> Proposed_By =
from project in xmldoc.Descendants("Projects").Elements("Project")
where project.Attribute("Country").Value == "Canada"
select project.Attribute("ProposedBy").Value;
I would however go a step further and also check if the attribute is there (since calling the Value
property on a null
object would result in an exception:
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;
First see if your file is getting make corrections to your linq query
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
与属性名称一起使用
Another Way: It returns NULL if Value is not present.
var Propposed_By = from project in xd.Descendants("Projects").Elements("Project")
where project.Attribute("Country").Value == "Canada"
select (string)project.Attribute("ProposedBy");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.