Command Line Parsing with XmlSerializer

Duncan Mackenzie commented about a command line switch parser he found. Has anyone thought of doing command line parsing using (my current favorite class) the XmlSerializer? The code that follows can handle strings, ints, uints, bools, enums and arrays. Best of all it's only a page of code!  The code you are about to see was designed using Ad Hoc tests.  The '_verbose' category is a hint to dump the object's fields and properties.  You can find more information about point and click testing here.


using System;

using System.IO;

using System.Xml;

using System.Xml.Serialization;

using System.Diagnostics;

using System.Text.RegularExpressions;

public class ComandLineParser

{

public static void TestParse()

{

string[] args = {"/one:111", "/two:xxx", "/two:yyy",

"T H R E E", "/choice:Yes"};

StringWriter writer = new StringWriter();

XmlWriter xmlWriter = new XmlTextWriter(writer);

xmlWriter.WriteStartElement("Parsed");

foreach(string arg in args)

{

Match match = Regex.Match(arg, @"/(?<name>.+):(?<val>.+)");

if(match.Success)

{

string name = match.Groups["name"].Value;

string val = match.Groups["val"].Value;

xmlWriter.WriteElementString(name, val);

}

else { xmlWriter.WriteString(arg); }

}

xmlWriter.WriteEndElement();

StringReader reader = new StringReader(writer.ToString());

XmlSerializer ser = new XmlSerializer(typeof(Parsed));

Parsed parsed = (Parsed)ser.Deserialize(reader);

 

Debug.WriteLine(parsed, "_verbose");

Debug.Assert(parsed.one == 111);

Debug.Assert(parsed.two[0] == "xxx");

Debug.Assert(parsed.two[1] == "yyy");

Debug.Assert(parsed.three == "T H R E E");

Debug.Assert(parsed.choice == Choice.Yes);

}

 

public class Parsed

{

[XmlElement] public int one;

[XmlElement] public string[] two;

[XmlText] public string three;

public Choice choice;

}

public enum Choice { No, Yes }

}

I've written a similar utility class that handles urls and query strings. This basically means you can reference pages in your site using custom url classes. It seems to work really well.

24 Comments

Comments have been disabled for this content.