XML regex C#

XML

XML stands for Extensible Markup Language and is used for storing arbitrary data. Usually, it’s not a good thing to parse XML with regular expressions, but in certain situations, it can be very helpful to retrieve (scrape) a specific piece of information that you need.

Extract value between XML tags

One of the most common operations with XML and regex is the extraction of the text between certain tags (a.k.a. scraping). For this operation, the following regular expression can be used.

new Regex("(?:<from.*?>)(.*?)(?:<\\/from>)")

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in C#:

using System.Text.RegularExpressions;
using System;
                    
public class Program
{
    public static void Main()
    {
        // Extract text between specific XML tag
        Regex extractHTMLRegex = new Regex("(?:<from.*?>)(.*?)(?:<\\/from>)");
        Match match = extractHTMLRegex.Match("<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>");
        if (match.Success)
        {
            Console.WriteLine(match.Groups[1].Captures[0].Value); // prints Jani
        }
    }
}

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Notes on regex XML extraction

While this extraction might be a good option in some cases, usually it’s better to use specific XML parsers for such tasks. In such case, once XML is validated and parsed, the required information can be retrieved using Document queries. For instance, in C# the following code can be used:

using System;
using System.Xml;
                    
public class Program
{
    public static void Main()
    {
        // Extract text between specific XML tag
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml("<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>");
        XmlNodeList fromNode = xmlDoc.GetElementsByTagName("from");
        Console.WriteLine(fromNode[0].InnerText); // prints Jani
    }
}