Linq to xml question

G

Guest

Hi all,

I have a xml document which contains:

<users>
<user id="000000126836">
<loginname>Bart</loginname>
</user>
<user id="600000126836">
<loginname>Piet</loginname>
</user>
</users>



Now I want to retreive just one user with a certain id. I have tried this
code but it doesn't retreive anything.

public string GetLoginName(string buttonID)
{
XDocument userList = XDocument.Load("users.xml");

var query =
from users in userList.Descendants("user")
where (string)users.Attribute("id") == buttonID
select new
{
loginname = (string)users.Element("loginname"),
};

return ?????????
}

Now my question is what is wrong with my query and how can i return the
Login

Thanks in advance,

Bart
 
T

Tim Jarvis

Hi all,

I have a xml document which contains:

<users>
<user id="000000126836">
<loginname>Bart</loginname>
</user>
<user id="600000126836">
<loginname>Piet</loginname>
</user>
</users>

Hi Bart,

<Maxwell Smart Voice> Missed it by that much />

private void button1_Click(object sender, EventArgs e)
{
XElement users = XElement.Load(@"C:\Temp\Users.Xml");
try
{

string login = (from xe in users.Descendants("user")
where (string)xe.Attribute("id") ==
"600000126835"
select
(string)xe.Element("loginname")).Single();
textBox1.Text = login;
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
}

This will give you an exception if the ID is not found that you can
then simply handle, or if you prefer you could use the SingleOrDefault
method to just return an empty string if not found.

Regards Tim.

--
 

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

Top