gpt4 book ai didi

c# - 选择通过与其分组的另一个属性值找到的 XML 属性值。

转载 作者:行者123 更新时间:2023-11-30 22:00:31 25 4
gpt4 key购买 nike

我对使用 XML 做任何事情都是全新的,所以我不太了解术语,对于这个可能措辞不当的问题,我深表歉意。

我有一个结构如下的 XML 文件:

<userinfo>
<id username="bobby" password="password123" email="booby@gmail.com" question="Favourite colour" answer="blue"></id>
<id username="tommy" password="adc123" email="herpderp@gmail.com" question="first pets name" answer="arnold"></id>
</userinfo>

(对此提出的任何改进建议将不胜感激)

我需要根据用户名将问题值检索为字符串。

我已经有一些与 xml 交互的代码,我在其中返回一个 bool 用于登录,它只是检查信息是否在一起:

public bool ValidLogin(string username, string password)
{
XDocument doc = XDocument.Load(@"K:\Sem2\Software Development in Application Frameworks\test stuff\text\loginDetails.xml");

return doc.Descendants("id")
.Where(id => id.Attribute("username").Value == username
&& id.Attribute("password").Value == password)
.Any();
}

但那是使用 linq,我不知道如何从 xml 中获取实际值。

如果它像下面这样的东西一样简单就好了:

 return doc.Descendants("id").Attribute("question").Value.Where(id => id.Attribute("username").Value == enteredUsername);

最佳答案

您需要使用 Select()First()Last()Single()获得值(value)。

理想情况下,您应该有一个与您的 XML 文件匹配的类:

public class UserInfo
{
public string username {get;set;}
public string password {get;set;}
public string question {get;set;}
public string email {get;set;}
public string answer {get;set;}
}

然后把你的方法改成这样:

public UserInfo GetUserInfo(string username, string password)
{
XDocument doc = XDocument.Load(@"K:\Sem2\Software Development in Application Frameworks\test stuff\text\loginDetails.xml");

return doc.Descendants("id")
.Where(id => (string)id.Attribute("username") == username
&& (string)id.Attribute("password") == password)
.Select(s => new UserInfo
{
username = (string)s.Attribute("username"),
password = (string)s.Attribute("password"),
email = (string)s.Attribute("email"),
question = (string)s.Attribute("question"),
answer = (string)s.Attribute("answer")
})
.FirstOrDefault();
}

现在在你的调用方法中:

var userInfo = GetUserInfo(username, password);

// check if user information matches what's in the XML file. return an error if it doesnt.
if (userInfo == null)
Console.WriteLine("incorrect username/password");

// you haven't clarified in your question what you're doing with it. But the value of 'question' is accessible like this:
Console.WriteLine(userInfo.question);

关于c# - 选择通过与其分组的另一个属性值找到的 XML 属性值。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com