hine32
hine32

Reputation: 3

Linq to XML file query not working

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

Upvotes: 0

Views: 56

Answers (4)

Thirisangu Ramanathan
Thirisangu Ramanathan

Reputation: 614

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");

Upvotes: 0

James
James

Reputation: 170

Use .Value with attribute names

Upvotes: 0

Andrei V
Andrei V

Reputation: 7508

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;

Upvotes: 1

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

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;

Upvotes: 0

Related Questions