Reputation: 93
Below is a sample xml file with the data i'm after
<ns2:Response/">
<cacheKey>-7ca7484a:13e22cb1399:-47c0</cacheKey>
<cacheLocation>10.186.168.39:7302</cacheLocation>
</ns2:Response>
I have 2 classes, 1 class for getting xml data, this class then passes the data to another class that will have many other classes which extract the data.
public static string GetXmlData()
{
string xmlPath = "url";
var wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.ContentType, "application/xml");
wc.Headers.Add(HttpRequestHeader.Accept, "application/xml");
var xmlData = wc.DownloadString(new Uri(xmlPath));
var xmlDoc = XDocument.Parse(xmlData);
return xmlDoc.ToString();
}
The second clas has the following
public class GetCacheKey
{
public string cacheKey { get; set; }
}
Below is where I'm having problem:
public IEnumerable<GetCacheKey> CacheKey()
{
var doc = XDocument.Parse(GetXMLData());
var xkey = from c in doc.Descendants("Response")
select new GetCacheKey()
{
cacheKey = (string)doc.Element("cacheKey").Value
};
return xkey;
}
In debugger, it returns Empty = "Enumeration yielded no results"
So how can I get the value of cacheKey?
Upvotes: 0
Views: 393
Reputation: 48506
There's actually two problems with your code. First of all, doc.Descendants("Response")
will not yield any results, because you've omitted the ns2
bit. Secondly, doc.Element("cacheKey").Value
should be c.Element("cacheKey").Value
:
XNamespace ns2 = "http://namespaceurihere";
var xkey = from c in doc.Descendants(ns2 + "Response")
select new GetCacheKey()
{
cacheKey = c.Element("cacheKey").Value
};
Not really an issue, but the string cast in your code was redundant.
The namespace URI should be whatever URI you removed from the XML when you edited it for posting. It confuses people however, because <ns2:Response/">
is not valid XML.
Upvotes: 1