Thursday, October 13, 2011

Read or parse XML using LINQ (XLinq)

XML Content:
    <item>   
    <title>Labor Warehouse Associates - Boston, Massachusetts</title>   
    <link>http//www.BostonRecruiter.com/job_display.php?alpha=17343491</link>   
    <description>Hudson Group is the #1 airport retailer operating in over 400    
    retail locations in most major airports, throughout the US and Canada.    
    While we are comprised of many     
    </description>   
    <guid>http//www.BostonRecruiter.com/job_display.php?alpha=17343491</guid>   
    <joblocation>   
    <jobcity>Boston</jobcity>   
    <jobstate>Massachusetts</jobstate>   
    <jobcountry>United States</jobcountry>   
    </joblocation>   
   </item>   
Code:
  string url = "your xml or rss link";  
  string xmlsource = client.DownloadString(url);  
  StringReader readString = new System.IOStringReader(xmlsource);  
  XDocument xmlDoc = XDocument.Load(readString);  
  //solution 1  
  var tutorials = from jobfield in xmlDoc.Descendants("item")  
  select new  
  {  
    jobtitle = (string) jobfield.Element("title"),  
    joburl = (string) jobfield.Element("link"),  
    desc = (string)jobfield.Element("description"),  
    city = (string)jobfield.Element("joblocation").Element("jobcity"),  
    state = (string)jobfield.Element("joblocation").Element("jobstate"),  
  };     
  //solution 2  
  var tutorials = from jobfield in xmlDoc.Descendants("item")  
  select new  
  {  
    jobtitle = jobfield.Element("title").Value,  
    joburl = jobfield.Element("link").Value,  
    desc = jobfield.Element("description").Value,  
    city = jobfield.Element("joblocation").Element("jobcity").Value,  
    state = jobfield.Element("joblocation").Element("jobstate").Value,  
  };  

0 comments:

Post a Comment