CURRENT PROJECTS
loading
CATEGORIES AND POSTS
loading
overset
DEVELOPMENT LOG FOR JIM PALMER
Posted 04/22/2008 in C#.NET


So we have a 3rd party API that's returning "XML" in as though it was a DTD-less WDDX or XML-RPC format. We need to convert this "XML" into native C#.NET objects. The solution is a bit on the "Perl Hackish" side of things - but the simplest and fastest method I could come up with was to parse the "XML" into a JSON object then into a Native C#.NET object. The JSON library of choice here is LitJson

The overset.com.CSMadness.xmlToJsonToObject() method will convert the
<>114848000000</><amount>0.00</amount><avs_addr>""YARR</avs_addr>
to
{"amount":"0.00","avs_addr":"\"YARR"}
.. while stripping out the completely invalid <> node. This will also consider all node values to be a string.
Yes - we have the problem of this not even being close to valid XML which completely rules out use of the System.Xml functionality.

Now the C# code to take the "XML" string and parse it into C#.NET object via LitJson's functionality:
// csc /r:LitJson.dll xmlToJsonToObject.cs
namespace com.overset {
	using LitJson;
	using System.Text.RegularExpressions;
	public class CSMadness {
		public JsonData xmlToJsonToObject () {
			string rStr = @"<>114848000000</><amount>0.00</amount><avs_addr>""YARR</avs_addr>";
			string rStr = Regex.Replace(Regex.Replace(Regex.Replace(responseData, @"\\", @"\\"), @"""", @"\"""), @"<>[^<]*</>", @"");
			rStr = "{" + Regex.Replace(rStr, @"<([^>]*)>([^<]*)<\/[^>]*>", @",""$1"":""$2""").Substring(1) + "}";
			return JsonMapper.ToObject( rStr );
		}
	}
}
comments
loading
new comment
NAME
EMAIL ME ON UPDATES
EMAIL (hidden)
URL
MESSAGE TAGS ALLOWED: <code> <a> <pre class="code [tab4|tabX|inline|bash]"> <br>
PREVIEW COMMENT
TURING TEST
gravatar