0

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

2
  • How do you load the xmldoc? And is it of XDocument or XmlDocument? Could be helpful if you showed the loading code as well. Commented Sep 10, 2014 at 6:45
  • @Jehof include </Projects> Commented Sep 10, 2014 at 9:31

4 Answers 4

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but i am not getting output
0

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;

1 Comment

Ya @V2Solutions- MS Team
0

Use .Value with attribute names

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.