JSON in XML attribute

I have to pass some data from a C# module to a Java-script module.

Now, There's this middle-man module that I don't control, and ultimately does is calls the external(c#) module, and returns back an xml structure, with the data from the c# module inside an XML attribute.

I tried to put a JSON string, "\/Date(1350323947917)\/"

which came from

    DateTime dt = DateTime.Now;

    JavaScriptSerializer serailzer = new JavaScriptSerializer();
    string dateTimeString = serailzer.Serialize(dt);

And it didn't fit into the attribute as valid XML.

What I could try to do is trim the quotes off the end of the string, but I'm not sure whether or not that would make it invalid JSON

My question is, Should I attempt to continue with this JSON route, or there any other pitfalls that I'm missing?

EDIT: I'd like to reiterate that It is not my program which is generating the XML.

Upvotes: 2

Views: 8817

Answers (3)

mohghaderi
mohghaderi

Reputation: 2650

You may use System.Security.SecurityElement class to escape characters.

    /// <summary>
    /// Escapes Json string to be included in an XML attribute
    /// </summary>
    /// <param name="jsonString">json string</param>
    /// <returns></returns>
    public static string EscapeJson(string jsonString)
    {
        return SecurityElement.Escape(jsonString);
    }

    /// <summary>
    /// Unescapes Json string from XML attribute value
    /// </summary>
    /// <param name="xmlString">xml string</param>
    /// <returns></returns>
    public static string UnescapeJson(string xmlString)
    {
        return new SecurityElement("", xmlString).Text;
    }

Upvotes: 3

Evert
Evert

Reputation: 99533

JSON must be UTF-8, so as long as you use UTF-8 encoded XML, this will work. Just make sure you properly escape the json for usage in an attribute. The only four characters you need to escape are <, >, &, ", which are escaped as &lt;, &gt;, &amp; and &quot;.

CDATA has problems. You still must escape certain sequences, and since json and xml should both be valid UTF-8, there's less risk when not using CDATA. What you want is what SGML calls PCDATA, which is exactly what a standard text attribute or xml nodeValue is.

So the answer of your question is simply escape your data - whatever it may be - for the container. In this case it's xml.

Upvotes: 7

paulsm4
paulsm4

Reputation: 121649

1) You need to spell "serializer" correctly or it won't work :)

2) You need to include your JSON data in a "CDATA" section in order for your XML file to hold it correctly.

3) Here are some links for writing CDATA from C#:

Upvotes: -1

Related Questions