0

所以我有我生成的这个 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('$')));
4

2 回答 2

0

以下代码为您提供匹配元素的帐号,

members.Where(x=> x.Element("AccountName").Value==validationName).Select(x=> x.Element("AccountNumber").Value).FirstOrDefault();
于 2013-06-11T19:22:08.317 回答
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);
        }
于 2013-06-11T20:03:19.290 回答