繁体   English   中英

使用LINQ在XML文件中搜索2个不同的元素

[英]using LINQ to search in 2 different elements in XML file

我想使用以下linq搜索,但要修改它,以便它也将搜索用户和管理员。

NAMEIDPASS是用于比较的字符串。 如果所有3匹配,则程序知道它是什么类型的用户,管理员或用户,并从那里移动。 否则,他不在任何列表中,将显示错误。

XElement xelement = XElement.Load(@"c:\user.xml");
IEnumerable<XElement> users = xelement.Elements();
foreach (var user in users)
{
  if((user.Element("Id").Value==ID)&&(user.Element("Username").Value==NAME)&&(user.Element("Password").Value==PASS))

}

xml文件是这样构建的:

<Data>    
    <UserList>
        <User Id="123" Username="abc" Password="abc123"></User>
    </UserList>
    <AdminList>
        <Admin Id="123" Username="abc" Password="abc123"></Admin>
    </AdminList>
</Data>    

您当前的代码使用LINQ to XML类,但实际上并没有使用任何LINQ查询。

你能做的是:

  1. 分别获取管理员和用户

     XDocument xDoc = XDocument.Load(@"c:\\user.xml"); var admins = xDoc.Root.Element("AdminList").Elements("Admin"); var users = xDoc.Root.Element("UserList").Elements("User"); 
  2. 将它们连接在一起:

     var adminsAndUsers = admins.Select(x => new { Element = x, Type = "Admin" }) .Concat(users.Select(x => new { Element = x, Type = "User" })); 
  3. 查询匹配用户的查询结果集合。 我使用(string)XAttribute强制转换而不是XAttribute.Value属性,因为它使用起来更安全(当属性不存在时不会抛出异常)。

     var user = adminsAndUsers.FirstOrDefault( x => (string)x.Element.Attribute("Id") == ID && (string)x.Element.Attribute("Username") == NAME && (string)x.Element.Attribute("Password") == PASS); 
  4. 检查查询结果

     if(user != null) { // user is there var type = user.Type; } else { // no user matches } 

尝试此解决方案

结构体

 public struct test
        {
            public bool isStudent;
            public string id;
            public string Username;
            public string Password;
        }



List<test>  users = doc.Descendants("User").Where(e => e.Attribute("Id").Value == "123").Select(e => new test{ isStudent = true, id = e.Attribute("Id").Value, Username = e.Attribute("Username").Value, Password = e.Attribute("Username").Value }).ToList();
              List<test>  admins = doc.Descendants("Admin").Where(e => e.Attribute("Id").Value == "123").Select(e => new test { isStudent = false, id = e.Attribute("Id").Value, Username = e.Attribute("Username").Value, Password = e.Attribute("Username").Value }).ToList();
            List<test> allTogether = users.Concat(admins).ToList();
            foreach (var xElement in allTogether)
            {
               //check if xElement property isStudent is true
            }

现在在所有列表中,您可以查看您需要的所有房产。

暂无
暂无

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

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