skip to Main Content

My source JSON file have : in the key as mentioned below

"Dimension 4 : 4 : 4" : "4k TV"

My JSON to XML converter fails as this is not allowed and throws this exception

System.Xml.XmlException: The ':' character, hexadecimal value 0x3A, cannot be included in a name.

What should be the proper way to convert this JSON in valid XML file?

I have tried normal conversion which does not work, and this should not be considered as namespace also as this is not namespace but just some text.

2

Answers


  1. Assuming you need to be able to preserve the data, the way I would approach this would be to write some normalization API that removes invalid characters (spaces, whatever else you find) or replaces them with other tokens, then if the name and normalized name are different, make use of an attribute in a custom xml namespace (typically aliased), so you end up with:

    <Dimension_4_4_4 mytool:name="Dimension 4 : 4 : 4"><!-- content --><Dimension_4_4_4>
    

    and then reverse this process as needed.

    Note however, that Dimension 4 : 4 : 4 seems a lousy name in either json or xml meanings.

    Login or Signup to reply.
  2. You may use

    with encodeSpecialCharacters : true to convert your JSON to XML:

    var node = JsonConvert.DeserializeXNode(json, null, false, 
                                            encodeSpecialCharacters : true);
    

    As explained in the docs, this parameter is:

    A value to indicate whether to encode special characters when converting JSON to XML. If true, special characters like ‘:’, ‘@’, ‘?’, ‘#’ and ‘$’ in JSON property names aren’t used to specify XML namespaces, attributes or processing directives. Instead special characters are encoded and written as part of the XML element name.

    The name is encoded using the standard .NET method XmlConvert.EncodeLocalName(String) and thus may be recovered using XmlConvert.DecodeName(String).

    Thus:

    var json = """{"Dimension 4 : 4 : 4" : "4k TV"}""";
    
    var node = JsonConvert.DeserializeXNode(json, null, false, 
                                            encodeSpecialCharacters : true);
    foreach (var child in node.Descendants())
    {
        var name = child.Name.LocalName;
        var originalName = XmlConvert.DecodeName(child.Name.LocalName);
        Console.WriteLine($"Encoded name: {name}"); //Dimension_x0020_4_x0020__x003A__x0020_4_x0020__x003A__x0020_4
        Console.WriteLine($"Original name: {originalName}"); //Dimension 4 : 4 : 4
    }
    

    Prints:

    Encoded name: "Dimension_x0020_4_x0020__x003A__x0020_4_x0020__x003A__x0020_4"
    Original name: "Dimension 4 : 4 : 4"
    

    Demo fiddle here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search