Donate

How To Read Or Parse XML Using LINQ And XLinq In C#

Hello,

Here's an example on how to read or parse XML file using LINQ and XLINQ in C#.
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>   
C# 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,  
  };  

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.