简体   繁体   中英

“context instance” for a XElement linq to XML query using a where clause

I want to return a list of string values from an XElement collection and I get this error when constructing my code and don't see what I'm missing. 在此处输入图片说明

Here's a section of the class I've written concering the problem:

private XElement _viewConfig;

public ViewConfiguration(XElement vconfig)
{

    _viewConfig = vconfig;
}

public List<string> visibleSensors()
{

    IEnumerable<string> sensors = (from el in _viewConfig
                                   where el.Attribute("type").Value == "valueModule"
                                         && el.Element.Attribute("visible") = true
                                   select el.Element.Attribute("name").Value);

    return sensors.ToList<string>();
}

The XElement collection is of the form

<module name="temperature" type="valueModule" visible="true"></module>
<module name="lightIntensity" type="valueModule" visible="true"></module>
<module name="batteryCharge" type="valueModule" visible="true"></module>
<module name="VsolarCells" type="valueModule" visible="false"></module>

First of all XElement is not an IEnumerable therefore the first line from el in _viewConfig is not valid. If this is coming from a valid XML file, I presume the <module> elements are contained inside a parent element (eg, <modules> ). If you make _viewConfig to point to modules then the following will work:

IEnumerable<string> sensors = (
    from el in _viewConfig.Elements()
    where el.Attribute("type").Value == "valueModule"
          && el.Attribute("visible").Value == "true"
    select el.Attribute("name").Value);

Also note that type of el is XElement , therefore it doesn't have a property called Element which I also removed from above (along with a few syntax errors that I had to fix: usage of == instead of = for comparison, and using string literal "true" instead of boolean true to compare the value of an attribute textual value).

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.

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