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
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:
and then reverse this process as needed.
Note however, that
Dimension 4 : 4 : 4
seems a lousy name in either json or xml meanings.You may use
JsonConvert.DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, bool encodeSpecialCharacters)
, orJsonConvert.DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, bool encodeSpecialCharacters)
, orXmlNodeConverter
withEncodeSpecialCharacters
specified to betrue
with
encodeSpecialCharacters : true
to convert your JSON to XML:As explained in the docs, this parameter is:
The name is encoded using the standard .NET method
XmlConvert.EncodeLocalName(String)
and thus may be recovered usingXmlConvert.DecodeName(String)
.Thus:
Prints:
Demo fiddle here.