Sonhja
Sonhja

Reputation: 8458

Problems converting from an object to XML in java

What I'm trying to do is to convert an object to xml, then use a String to transfer it via Web Service so another platform (.Net in this case) can read the xml and then deparse it into the same object. I've been reading this article:

http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#start

And I've been able to do everything with no problems until here:

Serializer serializer = new Persister();
PacienteObj pac = new PacienteObj();
pac.idPaciente = "1";
pac.nomPaciente = "Sonia";
File result = new File("example.xml");
serializer.write(pac, result);

I know this will sound silly, but I can't find where Java creates the new File("example.xml"); so I can check the information.

And I wanna know if is there any way to convert that xml into a String instead of a File, because that's what I need exactly. I can't find that information at the article.

Thanks in advance.

Upvotes: 1

Views: 1171

Answers (3)

Andreas Dolk
Andreas Dolk

Reputation: 114807

You can use an instance of StringWriter:

Serializer serializer = new Persister();
PacienteObj pac = new PacienteObj();
pac.idPaciente = "1";
pac.nomPaciente = "Sonia";

StringWriter result = new StringWriter();
serializer.write(pac, result);
String xml = result.toString();  // xml now contains the serialized data

Upvotes: 3

Thilo
Thilo

Reputation: 262714

And I wanna know if is there any way to convert that xml into a String instead of a File, because that's what I need exactly. I can't find that information at the article.

Check out the JavaDoc. There is a method that writes to a Writer, so you can hook it up to a StringWriter (which writes into a String):

 StringWriter result = new StringWriter(expectedLength);
 serializer.write(pac, result)
 String s = result.toString();

Upvotes: 5

user425367
user425367

Reputation:

Log or print the below statement will tell you where the file is on the file system.

result.getAbsolutePath()

Upvotes: 1

Related Questions