Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- class ExtractInfoFromXMLFile
- {
- //Write a program that extracts from given XML file all the text without the tags. Example:
- //<?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>
- static void Main()
- {
- string inputFileName = "myText.txt"; //Full path to the file.If only a file name, then the file should be in the bin directory
- List<string> TextList = new List<string>();//List to store the clear content
- string xmlContent = ""; //String to stote file content
- int startIndex = 0, //Index to search for a tag characters
- lengthToEnd = 0,//This will store the length of the substring
- tempIndex = 0;//Index to search for a tag characters
- using (StreamReader readInputFile = new StreamReader(inputFileName))
- {
- xmlContent = readInputFile.ReadToEnd();//Read the whole file
- }
- while (tempIndex != -1)//While tempIndex returns a position for our tags
- {
- tempIndex = xmlContent.IndexOf('>', startIndex); //Find closing tag character
- if (tempIndex == -1) //If not found, break the cycle
- {
- break;
- }
- startIndex = tempIndex + 1; // Our substring should start from the next to the found position index
- tempIndex = xmlContent.IndexOf('<', startIndex); //Find opening tag character
- if (tempIndex == -1)//If not found, break the cycle
- {
- break;
- }
- if (tempIndex - startIndex > 1)//If there is something between the closing and opening tags >something<
- {
- lengthToEnd = tempIndex - startIndex; //Calculate the length of the substring
- TextList.Add(xmlContent.Substring(startIndex, lengthToEnd).Trim()); //Add the substring to the list. The Trim removes any white spaces before and after it
- }
- startIndex = tempIndex + 1; //Increase the startIndex for the next search
- lengthToEnd = 0;//Clear the length
- }
- using (StreamWriter writeOutputFile = new StreamWriter (inputFileName))
- {
- foreach (string line in TextList)
- {
- writeOutputFile.WriteLine(line);//Write the contents from our List by replacing the original file content
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement