Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 248
Sam I am says Reinstate Monica Avatar asked Aug 09 '26 16:08

Sam I am says Reinstate Monica


2 Answers

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.

like image 149
Evert Avatar answered Aug 12 '26 06:08

Evert


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;
    }
like image 22
mohghaderi Avatar answered Aug 12 '26 05:08

mohghaderi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!