My Technical Notes

Monday, 30 September 2013

Extracting an XML Element from a String

If you need to extract an XML element from a string, which is unique, (and no CTAGs in the document) without loading it into a document, copy and paste the following code:


public static string ExtractElement(string xml, string tagName) 
{
   var startTag = string.Format("<{0}>", tagName);
   var endTag = string.Format("</{0}>", tagName);

   var startIndex = xml.IndexOf(startTag);
   var endIndex = xml.IndexOf(endTag) + endTag.Length - 1;

   return xml.Substring(startIndex, endIndex - startIndex + 1);
}

No comments: