“Is XML fragment” Regex / Extension Method

Here’s a small extension method to roughly determine if a string contains an XML fragment (it’s not foolproof, but is usually adequate):

private static Regex isXmlFragment = new Regex( @"<([^>]+)>(.*?</(\1)>|[^>]*/>)" );

public static bool IsXmlFragment( this string content )
{
    return isXmlFragment.IsMatch( content );
}

Of course you could just use the regular expression by itself if you prefer… 🙂

One Comment

Leave a comment