所以我生成了这个XML文件,它看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<Members xmlns="urn:lst-emp:emp">
<Member xmlns="">
<!--Info for Member TESTER-->
<AccountName>Test Name</AccountName>
<AccountNumber>Test Number</AccountNumber>
<AccountBalance>Test Balance</AccountBalance>
</Member>
<Member xmlns="">
<!--Info for Member Jeff Reed-->
<AccountName>Jeff Reed</AccountName>
<AccountNumber>5929</AccountNumber>
<AccountBalance>9223.01</AccountBalance>
</Member>
</Members>
我可以使用下面的方法在整个XML中搜索AccountName,但在它作为匹配后,我需要一种方法来获得相应的xElements AccountNumber以验证它的PIN(帐号)是否等于我的密码文本框。
internal static bool userExists(String validationName)
{
bool foundUser = false;
//check for a name
XElement xelement = XElement.Load(Application.LocalUserAppDataPath + "\\members.xml");
IEnumerable<XElement> members = xelement.Elements();
foreach (var member in members)
{
if (member.Element("AccountName").Value == validationName)
{
//MessageBox.Show("It's a match.");
foundUser = true;
return foundUser;
}
else
{
//MessageBox.Show("No match found.");
}
}
return foundUser;
}
我该怎么做呢?我已经考虑过将它变回我的BankMember对象,但我需要一种方法来首先解析匹配用户名中的信息。
BankMember newMember = new BankMember(txtBxAccountName.Text.ToString(), int.Parse(txtBxAccountNumber.Text), float.Parse(txtBxStartingBalance.Text.TrimStart('$')));
答案 0 :(得分:0)
以下代码为您提供匹配元素的帐号
members.Where(x=> x.Element("AccountName").Value==validationName).Select(x=> x.Element("AccountNumber").Value).FirstOrDefault();
答案 1 :(得分:0)
父母是关键。像这样:
internal static XElement FindMember(String validationName)
{
XDocument doc = XDocument.Load(Application.LocalUserAppDataPath + "\\members.xml");
XElement accountNameElement = doc.Root
.Elements("Member")
.Elements("AccountName")
.FirstOrDefault(e => e.Value == validationName);
if (accountNameElement != default(XElement))
return accountNameElement.Parent;
return default(XElement);
}
这样调用:
XElement memberElement= FindMember("Test Name");
if (memberElement== default(XElement))
Console.WriteLine("Not Found");
else
{
Console.WriteLine("Found {0}, {1}, {2}"
, memberElement.Element("AccountName").Value
, memberElement.Element("AccountNumber").Value
, memberElement.Element("AccountBalance").Value);
}