简体   繁体   中英

I cant get the values from xml document

I have an xml file looks like this

<Accounts>
  <Account Id="1">
    <UserName>xxx@Hotmail.com</UserName>
    <Password>xxx</Password>
    <AddingDate>06 Mart 2015 Cuma</AddingDate>
    <AccountType>Hotmail</AccountType>
  </Account>

And class named KeyValuePairCls for stroing username and password values .I am trying to get theese values from xml document and save them into a list like this below .The problem is that I can get ony usernames not the password .What am i misiing out.

   private void AddAccounts()
        {
            List<KeyValuePairCls> _keyValue = new List<KeyValuePairCls>();
            XDocument doc = XDocument.Load("UserAccounts.xml");
            for (int i = 0; i < doc.Descendants("Account").Count(); i++)
            {

                _keyValue.Add(new KeyValuePairCls(doc.Descendants("Account").ElementAt(i).Element("UserName").Value,
               doc.Descendants("Account").ElementAt(i).Element("Password").Value
                        ));

            }

What you want is something like

string p = @"<Accounts>
  <Account Id='1'>
    <UserName>xxx@Hotmail.com</UserName>
    <Password>xxx</Password>
    <AddingDate>06 Mart 2015 Cuma</AddingDate>
    <AccountType>Hotmail</AccountType>
  </Account>
</Accounts>";
//I'm parsing a string instead of loading from a file but you get the same
// object back so don't worry 
var xdoc = XDocument.Parse(p);

var x = xdoc.Root.Elements("Account").Select (r => new { UserName = (string)r.Element("UserName"), Password = (string)r.Element("Password") });

Where you just iterate over the var x, you can create an object and say that you want a new MyObject instead if you want a IEnumerable of MyObject (good if you want to pass on the data), if you want the whole element instead of just the values just remove the casts (boxing, IE the (string))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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