4.22.08 Convert Single Level “XML” To Native C#.NET Object Via Json And Regular Expressions

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 is LitJson

Here’s an example of our “XML”:

<>114848000000</>
<amount>0.00</amount>
<avs_addr>""YARR</avs_addr>

Download this code: xmlToJsonToObject.xml

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 );
        }
    }
}

Download this code: xmlToJsonToObject.cs

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.


No comments




0.280s