繁体   English   中英

使用where子句的XElement linq to XML查询的“上下文实例”

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

我想从XElement集合返回一个字符串值列表,并且在构造代码时收到此错误,但看不到我所缺少的内容。 在此处输入图片说明

这是我编写的属于该问题的课程的一部分:

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>();
}

XElement集合的形式为

<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>

首先, XElement不是IEnumerable因此from el in _viewConfig的第一行无效。 如果这来自有效的XML文件,则假定<module>元素包含在父元素(例如<modules> )内。 如果使_viewConfig指向modules则将执行以下操作:

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

还要注意, el类型是XElement ,因此它没有称为Element的属性,我也从上面删除了该属性(以及一些我必须修复的语法错误:使用==代替=进行比较,并使用字符串文字"true"而不是布尔值true以比较属性文字值的值)。

暂无
暂无

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

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