Tyson
Tyson

Reputation: 13

LINQ to XML parsing using attributes

I have an xml file like this:

<users>
    <user name="user" password="123" email="[email protected]"/>
</users>

I need to write a code to copy the attribute values to a object type variable and I can't find anything which suits my needs. some part of the code which I have successfully written is:

public static UserInfo GetUser()
{
    XDocument users = XDocument.Load(FilePath.UserConfigurationPath);

    UserInfo usersvar = new UserInfo();
}

Here I have to return the object and compare it with a textbox value.

Can anybody please tell me how I can copy the values to the object?

Upvotes: 1

Views: 376

Answers (1)

abatishchev
abatishchev

Reputation: 100288

To parse all the users:

IEnumerable<UserInfo> GetUsers()
{
    XDocument users = XDocument.Load(path);

    return from u in users.Descendants("user")
           select new UserInfo
           {
               Name = (string)u.Attribute("name"),
               Password = (string)u.Attribute("password"),
               Email = (string)u.Attribute("email")
           };
}

IEnumerable<UserInfo> users = GetUsers();
UserInfo userUser = users.FirstOrDefault(u => u.Name == "user");

If the document contains exactly one user or you want to parse exactly the first:

XElement userElement = users.Descendants("user").FirstOrDefault();
if (userElement != null)
{
    UserInfo user = new UserInfo
    {
        Name = (string)userElement .Attribute("name"),
        Password = (string)userElement .Attribute("password"),
        Email = (string)userElement .Attribute("email")
    };
}

Upvotes: 3

Related Questions