使用Linq与xml查询比较XML

时间:2013-07-19 22:14:31

标签: c# xml linq

我有以下XML文件:

<?xml version="1.0" encoding="utf-8"?>
<Users>
<User>
  <Username> Admin </Username>
  <Password> 123 </Password>
<User>
</Users>

我需要在找到用户名元素时查找变量,然后我必须将其密码与我在另一个变量中的密码进行比较,并检查它们是否匹配。

有什么好方法可以做到以下几点?如果您需要更改XML文件的格式,只要它包含用户名/密码就没问题。

1 个答案:

答案 0 :(得分:3)

您不应将密码存储在纯XML中;但是,我认为这是你正在寻找的那种比较:

var userSought = "userA";
var passwordSought = "1234";

XDocument xml = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Users",
        new XElement("User",
            new XElement("Username", "Admin"),
            new XElement("Password", "123")),
        new XElement("User",
            new XElement("Username", "userA"),
            new XElement("Password", "123"))
        ));

var userMatch = (from userElement in xml.Element("Users").Elements("User")
                  where userElement.Element("Username").Value == userSought
                  select new
                  {
                      Username = userElement.Element("Username").Value,
                      Password = userElement.Element("Password").Value
                  }).FirstOrDefault();

if(userMatch.Username == userSought && userMatch.Password == passwordSought)
    Console.WriteLine(userSought + " matches password " + passwordSought);
else
    Console.WriteLine(userSought + " has password " + userMatch.Password + " but is expected to be " + passwordSought);