let say i have the following xml file
<Users>
<User>
<Name>David</Name>
<Date>9/30/2012 10:52:00 PM</Date>
</User>
<User>
<Name>David</Name>
<Date>9/30/2012 11:02:05 PM</Date>
</User>
<User>
<Name>David</Name>
<Date>9/30/2012 11:52:00 PM</Date>
</User>
<User>
<Name>Michelle</Name>
<Date>9/30/2012 11:02:13 PM</Date>
</User>
<User>
<Name>Michelle</Name>
<Date>9/30/2012 11:02:54 PM</Date>
</User>
</Users>
I will like to read the last date of David and put it on a string in my C# program, in this case it will be "9/30/2012 11:52:00 PM" I have the following code which is suppose to read the date of a particular User, but it is not working
public void readLastDate(string name)
{
string filePaths = "logins.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePaths);
xmlDoc.DocumentElement.SetAttribute("searching",name);
XmlNodeList tests = xmlDoc.SelectNodes("//Users[Name =/*/@searching]/User");
foreach (XmlNode test in tests)
{
string myDate = test.SelectSingleNode("LoginDate").InnerText;
InfoBox.Items.Add("Last Date:" + myDate);
}
Also, how would i handle an error if i want to read a date of a user that is not in the xml file. }
You can use LINQ to XML, example is how to read the last date of David
var xDoc = XDocument.Load("logins.xml");
var userElements = xDoc.Descendants("User")
.Where(x => x.Element("Name").Value == "David")
.ToList();
if (userElements.Any())
{
string lastDate = userElements.Select(x =>
DateTime.Parse(x.Element("Date").Value))
.OrderByDescending(x => x)
.First()
.ToString();
}
More information: