Convert XML to JsonValue?

Topics: jQuery
Nov 3, 2011 at 2:23 PM

Is there a way to convert XML in string form to a JsonValue object?  I can convert from JsonValue to XML by doing this:

using (var ms = new MemoryStream()) {                     
    using (var xdw = XmlDictionaryWriter.CreateTextWriter(ms)) {       
        return Encoding.UTF8.GetString(ms.ToArray());                     

I am having real trouble trying to go the other way without having to use the Json.NET library.  I don't have a problem with that library but I would rather not have to include it just for this one situation.  Thanks!

Nov 3, 2011 at 4:06 PM

I suppose you could:

· Deserialize the XML using the DataContractSerializer

· Serialize to JSON using the DataContractJsonSerializer

· Parse the JSON using JsonValue

Daniel Roth

Nov 3, 2011 at 4:17 PM

Thanks Dan.  Sorry if this was an obvious answer but I just started playing with WCF and the Web API.

Nov 3, 2011 at 4:34 PM

Rest assured that having to go through three serialization episodes to convert some XML to JSON is by no means an obvious answer J.

Daniel Roth

Nov 3, 2011 at 5:16 PM

Using your response I got everything going doing this:

using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlElement.ToString()))) {
    var reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
    var jsonValue = JsonValueExtensions.Load(reader);
Really pretty simple.  Thanks for your help.