Reputation: 25
I have a login page where the user chooses their name from a dropdown list then enters their id code in a text box. The page then redirects to the account page where the user's information is displayed. The dropdown list and the text box are being loaded and checked against an xml file, here's an example from it.
<staff>
<idcode>0200</idcode>
<Name id="0200">Doe, John</Name>
</staff>
I want the account page to check for the id attribute in the Name node to display the user's name in a label. I've tried using the method described here: C# Linq to XML query, but the output to the label I get is this "System.Linq.Enumerable+WhereEnumerableIterator`1[System.Xml.Linq.XElement]". Here's my code:
XDocument xdoc = XDocument.Load(Server.MapPath("Staff.xml"));
var result = xdoc.Descendants("Staff").Elements("Name").Where(n => n.Attribute("id").Value == inputPassword);
nameLabel.Text = result.ToString();
inputPassword is the idcode from the previous page and that loads correctly.
Am I missing something simple or would it be easier to restructure the xml so that the Name node is a child of the idcode node? Thanks.
Upvotes: 2
Views: 5065
Reputation: 236268
If you need to select name by given id, then you need two more things - select only one element from result, and get value of this name element:
string name = xdoc.Descendants("Staff")
.Elements("Name")
.Where(n => (string)n.Attribute("id") == inputPassword)
.Select(n => (string)n) // get element's value
.FirstOrDefault(); // select only first value, if any
Or with XPath
string xpath = String.Format("//Staff/Name[@id='{0}']", inputPassword);
string name = (string)xdoc.XPathSelectElement(xpath);
Upvotes: 2
Reputation: 16066
If you want to get the idcode I'd try something like this:
XDocument xdoc = XDocument.Load(Server.MapPath("Staff.xml"));
var result = xdoc.Descendants("Staff").Elements("idcode").Where(n => n.Value.ToString() == inputPassword).SingleOrDefault();
nameLabel.Text = result.ToString();
Upvotes: 0
Reputation: 1804
LINQ queries return iterators, to resolve it you need to add another method call, like Single()
or ToList()
. Try adding a Single() to the end of the call
XDocument xdoc = XDocument.Load(Server.MapPath("Staff.xml"));
var result = xdoc.Descendants("Staff").Elements("Name").Where(n => n.Attribute("id").Value == inputPassword).Single();
nameLabel.Text = result.ToString();
You could also use SingleOrDefault()
to avoid a NRE
Upvotes: 0