Wednesday, July 24, 2013

Extract text between Tags

Here is the function, useful for extracting strings from xml files:

string ExtractString(string s, string tag)
    {     
      var startTag = "<" + tag + ">";
      int startIndex = s.IndexOf(startTag) + startTag.Length;
      int endIndex = s.IndexOf("</" + tag + ">", startIndex);
      return s.Substring(startIndex, endIndex - startIndex);
}

Example of call:

string initial = "<Create>Text to retrieve</Create>";
textToRetrieve=ExtractString(initial,"Create");

Result:
The value of textToRetrieve will be "Text to retrieve".


No comments:

Post a Comment