'Java - Convert JSON to XML keeping the attributes

Using the org.json json library, it's easy to convert from XML to JSON. but the conversion back to XML always convert JSON attributes into XML nodes:

import org.json.JSONObject;
import org.json.XML;

public class Test {
    public static void main(String[] args) throws Exception {
        String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
        System.out.println(xml);

        JSONObject str = XML.toJSONObject(xml);
        System.out.println(str);

        JSONObject json = new JSONObject(str.toString());
        String xml2 = XML.toString(json);
        System.out.println(xml2);
    }
}

Output

<tag1 attr1="val1"><tag2 attr2="val2"/></tag1>
{"tag1":{"attr1":"val1","tag2":{"attr2":"val2"}}}
<tag1><attr1>val1</attr1><tag2><attr2>val2</attr2></tag2></tag1>

How can I retrieve my XML attributes?



Solution 1:[1]

Underscore-java has static methods U.xmlToJson(xml) and U.jsonToXml(json). Live example

import com.github.underscore.U;

public class Test {
    public static void main(String[] args) {
        String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
        System.out.println(U.xmlToJson(xml));
        System.out.println(U.jsonToXml(U.xmlToJson(xml)));
    }
}

// {
//   "tag1": {
//     "-attr1": "val1",
//     "tag2": {
//       "-attr2": "val2",
//       "-self-closing": "true"
//     }
//   },
//   "#omit-xml-declaration": "yes"
// }

Solution 2:[2]

If you would convert below XML

<tag1><attr1>val1</attr1><tag2><attr2>val2</attr2></tag2></tag1> 

you would get the same JSON result;

{"tag1":{"attr1":"val1","tag2":{"attr2":"val2"}}}

so converting back from JSON to XML could cause an ambiguity. Therefore it is better to write some custom codes indicating that if a json field and an attribute or a tag. I'm not sure if there is a library for that converting but this link might be helpful;

http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ahmet Kutlu