简体   繁体   中英

Retrieve attribute value from xml with c#

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()
                         }
                 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM