Advertisement
sylviapsh

Extract Info From XML File

Jan 27th, 2013
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.34 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5.  
  6. class ExtractInfoFromXMLFile
  7. {
  8.   //Write a program that extracts from given XML file all the text without the tags. Example:
  9.   //<?xml version="1.0"><student><name>Pesho</name> <age>21</age><interests count="3"><interest> Games</instrest><interest>C#</instrest><interest> Java</instrest></interests></student>
  10.  
  11.   static void Main()
  12.   {
  13.     string inputFileName = "myText.txt"; //Full path to the file.If only a file name, then the file should be in the bin directory
  14.     List<string> TextList = new List<string>();//List to store the clear content
  15.     string xmlContent = ""; //String to stote file content
  16.     int startIndex = 0, //Index to search for a tag characters
  17.         lengthToEnd = 0,//This will store the length of the substring
  18.         tempIndex = 0;//Index to search for a tag characters
  19.  
  20.     using (StreamReader readInputFile = new StreamReader(inputFileName))
  21.     {
  22.       xmlContent = readInputFile.ReadToEnd();//Read the whole file
  23.     }
  24.     while (tempIndex != -1)//While tempIndex returns a position for our tags
  25.     {
  26.       tempIndex = xmlContent.IndexOf('>', startIndex); //Find closing tag character
  27.       if (tempIndex == -1) //If not found, break the cycle
  28.       {
  29.         break;
  30.       }
  31.  
  32.       startIndex = tempIndex + 1; // Our substring should start from the next to the found position index
  33.  
  34.       tempIndex = xmlContent.IndexOf('<', startIndex); //Find opening tag character
  35.       if (tempIndex == -1)//If not found, break the cycle
  36.       {
  37.         break;
  38.       }
  39.  
  40.       if (tempIndex - startIndex > 1)//If there is something between the closing and opening tags >something<
  41.       {
  42.         lengthToEnd = tempIndex - startIndex; //Calculate the length of the substring
  43.         TextList.Add(xmlContent.Substring(startIndex, lengthToEnd).Trim()); //Add the substring to the list. The Trim removes any white spaces before and after it
  44.       }
  45.       startIndex = tempIndex + 1; //Increase the startIndex for the next search
  46.       lengthToEnd = 0;//Clear the length
  47.     }
  48.     using (StreamWriter writeOutputFile = new StreamWriter (inputFileName))
  49.     {
  50.       foreach (string line in TextList)
  51.       {
  52.         writeOutputFile.WriteLine(line);//Write the contents from our List by replacing the original file content
  53.       }
  54.     }
  55.   }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement