2

Possible Duplicate:
Create XML file using java

In Java to create the JSONObject {"box":"tissue","desk":"wood"} all I need to do is

JSONObject json = new JSONObject();
json.put("box","tissue");
json.put("desk","wood");

And to create the JSONObject {"my-stuff":{"box":"tissue","desk":"wood"}} all I need to do is

JSONObject json = new JSONObject();
json.put("box","tissue");
json.put("desk","wood");

JSONObject myStuff = new JSONObject();
myStuff.put("my-stuff",json);

Then to get the String representations back, I just do json.toString() or myStuff.toString().

I happen to be using org.codehaus.jettison.json.JSONObject; but really that's how JSONObject works.

Is there an equivalently simple way to create XML in Java? If not, still, what's the simplest way to do what I just did -- in XML?

Community
  • 1
  • 1
kasavbere
  • 5,873
  • 14
  • 49
  • 72

4 Answers4

3

I'd suggest Dom4J:

Element root = DocumentHelper.createElement("my-stuff")
Document dom = DocumentHelper.createDocument(root);
root.addElement("box").setText("tissue");
System.out.println(dom.asXml());
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
2

Surely there is, but if you already have a bunch of json code written anyways, I would suggest simply turning your json into xml, like this: http://answers.oreilly.com/topic/279-how-to-convert-json-to-xml-in-java/

I apologize for not answering your question directly, but unless you've implemented a serialization wrapper, just turning the json into xml is going to save a ton of development time (as opposed to duplicating every line of code where you're adding/pulling from your json objects or - as I alluded to earlier - implementing a serialization wrapper).

Dave
  • 6,141
  • 2
  • 38
  • 65
  • Thanks for the suggestiong. I am confident someone will find it useful. But I don't have json objects. – kasavbere Oct 13 '12 at 17:39
  • 2
    I think this is very useful when you have JSON objects. On the other hand, @kasavbere, I think you can produce your JSONObjects and JSONArrays first, just like you explained on your question, then you can convert them to XML. – Yasin Okumuş Oct 13 '12 at 17:41
  • That's a great thought. Thanks. – kasavbere Oct 13 '12 at 17:47
1

have you tried Xstream? If you have a well modeled class, then its trivial to generate the xml as a string. You can also customize the output by using annotations.

sreeni
  • 141
  • 7
0

Also, check out Groovy (which is compatible with Java), and it's MarkupBuilder. For an example, see http://www.ibm.com/developerworks/java/library/j-pg05199/

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67