Advertisement
hristo_bratanov

Extract Content Between Tags

Jan 30th, 2013
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3.  
  4. class ExtractContentBetweenTags
  5. {
  6.     static void Main()
  7.     {
  8.         string html = @"<html><head><title>News</title></head><body><p><a href=""http://academy.telerik.com"">TelerikAcademy</a>aims to provide free real-world practical training for young people who want to turn into skillful .NET software engineers.</p></body></html>";
  9.        
  10.     StringBuilder result = new StringBuilder();
  11.         int indexOfTitle = html.IndexOf("<title>");
  12.         int indexOfEndOfTitle = indexOfTitle + 6;
  13.  
  14.     // check for content in title
  15.         for (int i = indexOfEndOfTitle + 1; i < html.Length; i++)
  16.     {
  17.             if (html[i] != '<')
  18.             {
  19.                 result.Append(html[i]);
  20.             }
  21.  
  22.             else
  23.             {
  24.                 break;
  25.             }
  26.  
  27.     }
  28.         result.AppendLine();
  29.  
  30.     // chack for content in body
  31.         int indexOfBody = html.IndexOf("<body>");
  32.         bool afterTag = false;
  33.  
  34.         for (int i = indexOfBody + 6; i < html.Length; i++)
  35.         {
  36.             if (afterTag)
  37.             {
  38.                 if (html[i] == '<')
  39.                 {
  40.                     afterTag = false;
  41.                 }
  42.  
  43.                 else
  44.                 {
  45.                     result.Append(html[i]);
  46.                     if (html[i+1] == '<')
  47.                     {
  48.                         result.AppendLine();
  49.                     }
  50.  
  51.                 }
  52.  
  53.             }
  54.             if (html[i] == '>' && i+1 < html.Length)
  55.             {
  56.                 afterTag = true;
  57.                 continue;
  58.             }
  59.  
  60.         }
  61.  
  62.         Console.WriteLine(result.ToString());
  63.        
  64.     }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement