Skip to content

Instantly share code, notes, and snippets.

@danielpeintner
Last active December 2, 2022 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpeintner/6b7c56f9fdf46db1ef3845862cc37c19 to your computer and use it in GitHub Desktop.
Save danielpeintner/6b7c56f9fdf46db1ef3845862cc37c19 to your computer and use it in GitHub Desktop.
XML <--> JSON

XML Rules

Questions

  • Shall we take into account XML or XML Schema (see issues below)

Links

Tools

Rules

  • JSON members whose names start with @ (or $) are transformed to XML attributes (TBD)
  • #text (or _) used for text content (TBD)
  • Simple types are always nested in a term
  • What about namespaces?
  • Multiple roots NOT possible in XML -> add outer root? Starting with XML this should not be an issue
  • need to always wrap JSON in root? Starting with XML this should not be an issue

XML to JSON

e.g., for reading XML int using JSON in scripts that then get converted to XML on the wire

XML JSON
<foo>1</foo> -> {"foo": "1"}
<root att="X">1</root> -> {"root": {"@att": "X", "#text": "1"}} OR {"root":{"$att":"X","_":"1"}}
<root><a>A</a><b>B</b></root> -> {"root": {"a": "A", "b": "B"}}
<root><a>A1</a><b>B1</b><a>A2</a><b>B2</b></root> -> {"root": {"a": ["A1", "A2"], "b": ["B1", "B2"]}} OR {"root": [{"a": "A1","b": "B1"},{"a": "A2","b": "B2"}]}
XML schema could tell that there can be multiple a+b sequences. Returning from JSON to XML might result in different result (first a's and then b's which is not the same).
<root at="dd"><a>A1</a><a>A2</a><b>B1</b><b>B2</b></root>
<nsX:Name xmlns:nsX="http://mycompany">Widget A</nsX:Name> -> {"nsX:Name":{"$xmlns:nsX":"http://mycompany","_":"Widget A"}}
... -> ...

JSON to XML

e.g., for using JSON in scripts that then get converted to XML on the wire

Note: ONLY specific JSON can be transformed to XML (see some fail below).

JSON XML
"string" -> FAIL given that XML needs surrounding element Starting with XML this should not be an issue
{"el": 123} -> <el>123</el>
{"el": 123, "@at": true} -> <el at="true">123</el> ??? at on this level or outside in root ??? Sample not valid, needs outer nesting for @? --> Fail Starting with XML this should not be an issue
{"el1": 1, "el2": 2, "@at": true} -> <root at="true"><el1>1</el1><el2>2</el2></root> root added because there cannot be multipe roots in XML!?! Starting with XML this should not be an issue
{"root":{"$att":"X","_":"1"}} -> <root att="X">1</root>
{"nsX:Name":{"$xmlns:nsX":"http://mycompany","_":"Widget A"}} -> <nsX:Name xmlns:nsX="http://mycompany">Widget A</nsX:Name>
... -> ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment