检测到LINQ to XML XElement无法访问的代码?

时间:2014-08-04 16:31:20

标签: c# xml linq

我正在尝试使用c#中的LINQ从XML文件中获取值,它正在给我一个警告

“类System.Xml.Linq.XElement表示XML元素。警告:检测到无法访问的代码”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;

namespace BDiamond
{
    public class Login
    {
        private string email ;
        private bool isValid = false;
        private string bdConfigFile = "BDiamond.xml";

        public bool VerifyEmail(string e)
        {
            string email = e;

            //Grab element values that match the Email attribute in XML file
            XElement root = XElement.Load(bdConfigFile);
            IEnumerable<XElement> list1 =
                from el in root.Elements()
                where el.Attribute("Email") != null
                select el;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我不确定您是否提供了实际的代码,但是您缺少的是return语句,并且它不是警告它是错误。显然,此代码不会生成任何警告。您可以在方法的末尾添加 return 语句,如下所示:

return list1.Any();

或者您可以在一个声明中这样做:

public bool VerifyEmail(string e)
{
     string email = e;

      //Grab element values that match the Email attribute in XML file
      XElement root = XElement.Load(bdConfigFile);
      return root.Elements().Any(el => (string)el.Attribute("Email") == email);
}

我想你应该将Email属性的值与参数email进行比较,否则它没有任何意义。如果你知道哪个元素拥有Email属性,你可以用这个:

return root.Descendants("ParentElement")
      .Any(el => (string)el.Attribute("Email") == email);

而不是遍历所有元素。