Search code examples
c#xmlxpathlinq-to-xmlxelement

select nodes with specific child node when xml can be different


I have code that's working, but I'd like to see if there's a nicer and better solution than what I have (I'm sure there is!). I have a webservice that needs to return all nodes that has a child node called "updatedDate" with a date more recent than the passed in date. The xml I'm returning can be different for each query, the only thing they have in common is the updatedDate node. I'm currently using linq to xml with xpath, here's the code:

XDocument allNodes = XDocument.Parse(result);

IEnumerable<XElement> nodesWithDates = allNodes.XPathSelectElements("//updatedDate");

XElement updatedNodes = new XElement("UpdatedNodes");

foreach (XElement node in nodesWithDates)
{
    DateTime date;

    if (DateTime.TryParse(node.Value, out date))
    {
        if (date > dateToCompare)
        {
            updatedNodes.Add(node.Parent);
        }
    }
}

return updatedNodes;

Any ideas on how to improve it?

Thanks,

Annelie


Solution

  • A somewhat different and more compact approach:

    DateTime date;
    var nodes = allNodes.Descendants("updatedDate")
                        .Where(x => DateTime.TryParse(x.Value, out date)
                                    && date > dateToCompare)
                        .Select(x => x.Parent);
    
    XElement updatedNodes = new XElement("UpdatedNodes", nodes);