Wednesday, November 9, 2011

Read or parse XML using XmlElement class and XmlNodelist

Sample xml file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<jobs>
   <job>
      <title>Payroll Analyst</title>
      <description>
         <summary>Seeking Payroll Analyst specialists.    
  Great benefits and competitive salary. Must meet all requirements    
  to be considered for assignment.</summary>
      </description>
      <location>
         <state>Pennsylvenia</state>
      </location>
   </job>
   <job />
</jobs>
Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
ListingSource = webclient.DownloadString("your_xmlurl");  
StringReader readString = new System.IOStringReader(ListingSource);  
XmlDocument awesome = new XmlDocument();  
awesome.Load(readString);  
XmlNodeList nodeList = awesome.SelectNodes("//jobs/job");  
foreach (XmlElement element in nodeList)  
{  
    title = element["title"].InnerText.Trim();  
    state_name_text = element["location"]["state"].InnerText.Trim();   
    description = element["description"]["summary"].InnerText.Trim();  
} 

1 comments: