1

I am having a problem parsing xml that I receive from Web Service.

The xml looks very simple:

<Result xsi:schemaLocation="urn:yahoo:developer http://developer.yahooapis.com/TimeService/V1/GetTimeResponse.xsd" type="web"><Timestamp>1320677359</Timestamp></Result>

But when I try to parse it with following code I am getting no return results.

 XDocument doc = XDocument.Load("http://developer.yahooapis.com/TimeService/V1/getTime?appid=StackSolution");           

            var datestamp = from ds in doc.Descendants("Result")
                            select new { currentstamp = ds.Element("Timestamp").Value };

Is there a solution or way to parse it?

Thanks you in advance

Dmitris
  • 3,408
  • 5
  • 35
  • 41

2 Answers2

3

You have a couple issues: First, the Result node isn't a descendant. It's the root. Second, you ran into the most common issue when using LINQ to XML - you forgot the namespace. The following should give you what you need:

XElement doc = XElement.Load("http://developer.yahooapis.com/TimeService/V1/getTime?appid=StackSolution");            
XNamespace ns = "urn:yahoo:developer";
var datestamp = from ds in doc.DescendantsAndSelf(ns + "Result") 
                select new { currentstamp = ds.Element(ns + "Timestamp").Value };

Note, this produces an IEnumerable. If you only want the datestamp, consider using FirstOrDefault instead. You may be able to make this simpler by just doing the following:

XElement doc = XElement.Load("http://developer.yahooapis.com/TimeService/V1/getTime?appid=StackSolution");            
XNamespace ns = "urn:yahoo:developer";
var datestamp = doc.Element(ns + "Timestamp").Value;
Jim Wooley
  • 10,169
  • 1
  • 25
  • 43
1

This method avoids the namespace issue using LocalName (unqualified identifier).

var datestamp = doc.Root.Descendants().Where(c => c.Name.LocalName.Equals("Timestamp")).FirstOrDefault().FirstNode.ToString()
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173