Create a complex type from Linq-to-XML

C

C.

Hi,

I have a User object with two properties, ID and Name

I have an XML file that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<Users>
<User>
<ID>4</ID>
<Name>Paul</Name>
</User>
<User>
<ID>3</ID>
<Name>John</Name>
</User>
<User>
<ID>2</ID>
<Name>George</Name>
</User>
<User>
<ID>1</ID>
<Name>Ringo</Name>
</User>
</Users>

I have a function that retrieves all users from the file and returns a
List<User>. Is this the best way to do this?

public List<User> GetUsers()
{
XDocument doc = XDocument.Load("path/to/file/xml");

var Users = from user in doc.Descendants("User")
select new
{
ID = user.Element("ID").Value,
Name = user.Element("Name").Value
};

List<User> UserList = new List<User>();

foreach (var currUser in Users)
{
UserList.Add(new User(Convert.ToInt32(currUser.ID),
currUser.Name));
}
return UserList;
}
 
M

Mr. Arnold

C. said:
Hi,

I have a User object with two properties, ID and Name

I have an XML file that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<Users>
<User>
<ID>4</ID>
<Name>Paul</Name>
</User>
<User>
<ID>3</ID>
<Name>John</Name>
</User>
<User>
<ID>2</ID>
<Name>George</Name>
</User>
<User>
<ID>1</ID>
<Name>Ringo</Name>
</User>
</Users>

I have a function that retrieves all users from the file and returns a
List<User>. Is this the best way to do this?

public List<User> GetUsers()
{
XDocument doc = XDocument.Load("path/to/file/xml");

var Users = from user in doc.Descendants("User")
select new
{
ID = user.Element("ID").Value,
Name = user.Element("Name").Value
};

List<User> UserList = new List<User>();

foreach (var currUser in Users)
{
UserList.Add(new User(Convert.ToInt32(currUser.ID),
currUser.Name));
}
return UserList;
}
.

var users = new List<Users>();

users = (from user in doc.Descendants("User")
select new
{
ID = user.Element("ID").Value,
Name = user.Element("Name").Value
}).ToList();

return users;

return (from user in doc.Descendants("User")
select new
{
ID = user.Element("ID").Value,
Name = user.Element("Name").Value
}).ToList();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top