简体   繁体   中英

Get object value from xml query in c#

I can't find out how to retrieve a value from my object. This is the code:

    private object GetUserData(XElement xmlDoc)
    {
        return
              xmlDoc.Descendants("UserData").Select(u => new
              {
                  UserName = u.Element("UserName").Value,
                  Pass = u.Element("Pass").Value,
                  CurTemplate = u.Element("CurrentTemplate").Value
              });
    }

this is getting stored in:

   var userData = GetUserData(xmlDoc);

when I debug this and open the userData value, it has one list with my definded properties but I simply can not achieve them. I tried to convert the return value into a list, dictionary, lookup, string and so on but this doesn't help at all. Can someone help?

Thank you!

You can't return Anonymous types, and faking it by returning "object" won't help at all with this. If you need properties outside of the scope where you define the Anonymous object, then an Anonymous object is NOT what you need, you need to define a class with the properties you need (UserName, Pass, CurTemplate) and select a new instance of that type instead of a new Anonymous type. Then you'll be able to return an IEnumerable from your method

public class UserData
{
     public string UserName;
     public string Pass;
     public string CurTemplate;
}

private IEnumerable<UserData> GetUserData(XElement xmlDoc)
{
    return
          xmlDoc.Descendants("UserData").Select(u => new UserData
          {
              UserName = u.Element("UserName").Value,
              Pass = u.Element("Pass").Value,
              CurTemplate = u.Element("CurrentTemplate").Value
          });
}

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