简体   繁体   中英

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.

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();

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

记录或打印以下语句将告诉您文件在文件系统上的位置。

result.getAbsolutePath()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM