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.
Published Friday, April 11, 2003 12:10 AM by Jamie Cansdale

Comments

# re: Command Line Parsing with XmlSerializer

Ok, that is really cool :)

Thursday, April 10, 2003 11:30 AM by Duncan Mackenzie

# re: Command Line Parsing with XmlSerializer

Unhandled Exception: System.ArgumentException: parsing "/(?.+):(?.+)" - Unrecognized grouping construct.

Parameter name: /(?.+):(?.+)

Looks like your Regex is broken or HTML has garbled your regex!!!

Friday, April 11, 2003 2:22 AM by Shakeel Mahate

# re: Command Line Parsing with XmlSerializer

You're right! I forgot to escape my <>'s. It should of cause have been...

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

Thanks! How embarrassing...

Friday, April 11, 2003 2:36 AM by Jamie Cansdale

# re: Command Line Parsing with XmlSerializer

Cool it works. And I learned a thing about Regex Groups

Friday, April 11, 2003 2:40 AM by Shakeel Mahate

# parsing command line parameters in c#

<p>You would think of all the nice features they have in .Net that parsing comand line parameters to a console ...

Tuesday, August 24, 2004 10:57 AM by TrackBack

# re: Command Line Parsing with XmlSerializer

Great idea Jamie.  I did encounter one minor problem with the regex however.  .+ is greedy so if the value contains a colon the name match group will include the start of the value up to that colon.  Example:

/path:c:\windows\system32

gets

name = path:c

val = \windows\system32

changing (?<name>.+)

to (?<name>\w+)

is one way to resolve this problem.

Friday, September 07, 2007 9:30 AM by Sheppard

# re: Command Line Parsing with XmlSerializer

york news <a href= http://barerube.cn >news lohan</a> [url=http://barerube.cn]news lohan[/url]

Monday, May 05, 2008 7:53 PM by ctl00$main$ctl09$ctl02$ctl02$ctl02$tbname

# re: Command Line Parsing with XmlSerializer

NConsoler is an open source library that provides command line parser functionality based on attribute metadata attached to type.

Library is very easy to add and use in your application. NConsoler gives an ability to display help and validation messages without any line of code.

http://nconsoler.csharpus.com/

Example code:

using System;

using NConsoler;

public class Program {

   public static void Main(params string[] args) {

       Consolery.Run(typeof(Program), args);

   }

   [Action]

   public static void Method(

       [Required] string name,

       [Optional(true)] bool flag) {

           Console.WriteLine("name: {0}, flag: {1}", name, flag);

  }

}

and use it:

program.exe "Maxim" /-flag

Monday, September 08, 2008 1:12 PM by tihobrazov

Leave a Comment

(required) 
(required) 
(optional)
(required)