简体   繁体   English

Linq to XML文件查询不起作用

[英]Linq to XML file query not working

This is my XML file and I am using linq and entity framework 这是我的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> 

the linq query I am using is 我正在使用的linq查询是

   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: 但是,我将进一步检查该属性是否存在(因为在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;

First see if your file is getting make corrections to your linq query 首先查看您的文件是否正在对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与属性名称一起使用

Another Way: It returns NULL if Value is not present. 另一种方式:如果不存在Value,则返回NULL。

 var Propposed_By = from project in xd.Descendants("Projects").Elements("Project")
                           where project.Attribute("Country").Value == "Canada"
                           select (string)project.Attribute("ProposedBy");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM