I am having trouble getting the attribute value from the xml. I am using Google Custom Search API.
var results =
(from r in res.Descendants("R")
where r.Element("T") != null
select new GoogleSearchResultItem(
new PageSummary
{
Title = r.Element("T").Value,
LinkURL = r.Element("U").Value,
Description = r.Element("S").Value
}));
It works fine with the T,U,S elements but when I try to get the attribute programid I get null.
here is the XML:
<R N="1">
<U>
Link to somepage
</U>
<T>
<b>Title</b>
</T>
<S>
Summary
</S>
<LANG>sv</LANG>
<Label>_cse_1h5bojdlb5c</Label>
<PageMap>
<DataObject type="metatags">
<Attribute name="displaydate" value="20121028"/>
<Attribute name="programid" value="2519"/>
<Attribute name="formatid" value="116"/>
</DataObject>
</PageMap>
I used an anonymous type here but nothing stopping you strongly typing it.
var res = XDocument.Load(@"c:\temp\test.xml");
var results = res.Descendants("R").Where(r => r.Element("T") != null)
.Select(r => new
{
Title = r.Element("T").Value,
LinkUrl = r.Element("U").Value,
Description = r.Element("S").Value,
ProgramId = r.Descendants("Attribute").Where(x=>x.Attribute("name").Value == "programid").Select(x=>x.Attribute("value").Value).FirstOrDefault()
}).ToList();
Here it is strongly typed
var res = XDocument.Load(@"c:\temp\test.xml");
var results = res.Descendants("R").Where(r => r.Element("T") != null)
.Select(r => new GoogleSearchResultItem
{
PageSummary = new PageSummary
{
Title = r.Element("T").Value,
LinkUrl = r.Element("U").Value,
Description = r.Element("S").Value,
ProgramId = r.Descendants("Attribute").Where(x => x.Attribute("name").Value == "programid").Select(x => x.Attribute("value").Value).FirstOrDefault()
}
});