Skip to content

Instantly share code, notes, and snippets.

@justinAurand
Last active December 26, 2015 10:39
Show Gist options
  • Save justinAurand/7138449 to your computer and use it in GitHub Desktop.
Save justinAurand/7138449 to your computer and use it in GitHub Desktop.
Get XML and/or HTML from file. Return the values of the supplied attribute name.
using System;
using System.IO;
using System.Text.RegularExpressions;
class GetAttributeValues
{
public static void Main()
{
// Program settings (at top for convenience since they're most likely to be modified).
string attributeName = "name";
string attributeValueRegex = @"(?<=\b" + attributeName + @"="")[^""]*";
string filePath = @"C:\xml.txt";
// Open file containing HTML and/or XML tags.
using (var streamReader = new StreamReader(filePath))
{
// Variable for holding line of text from file.
string line;
// Read the file line by line.
while ((line = streamReader.ReadLine()) != null)
// Write the attribute value to the console.
Console.WriteLine(GetRegexMatch(line, attributeValueRegex));
}
// Suspend the screen.
Console.ReadKey();
}
public static string GetRegexMatch(string text, string regexPattern)
{
// Instantiate regex object and execute.
Regex regex = new Regex(regexPattern);
Match match = regex.Match(text);
// Return the matched text.
return match.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment