Israel Rodriguez
Israel Rodriguez

Reputation: 209

Getting last element of an xml file

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. }

Upvotes: 2

Views: 4904

Answers (3)

Enigmativity
Enigmativity

Reputation: 117084

I too would use Linq-to-XML. I think my approach is pretty clean.

var result =
    XDocument
        .Load(fileName)
        .Element("Users")
        .Elements("User")
        .Where(xe => xe.Element("Name").Value == "David")
        .Select(xe => DateTime.Parse(xe.Element("Date").Value))
        .OrderByDescending(d => d)
        .FirstOrDefault();

if (result == default(DateTime))
{
    /* no value */
}

Upvotes: 0

barefootliam
barefootliam

Reputation: 619

In XPath, (/Users/User[Name = 'David'])[position() = last()]

However, first you must fix the errors in your XML file ;-)

Upvotes: 2

cuongle
cuongle

Reputation: 75306

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:

http://msdn.microsoft.com/en-us/library/bb387098.aspx

Upvotes: 2

Related Questions