2

I would like to convert a Java Object to a String containing the marshaled XML data. One of the ways I could find was to first marshal to a File and then read the file using BufferedReader to convert into a String. I feel this may not be the most efficient way, because the IO operations are performed twice (Once during marshaling and the second time during the conversion of file content into String)

Could anyone please suggest any better approach?

2 Answers 2

8

Pass a StringWriter object as argument to marshal method of Marshaller

Sign up to request clarification or add additional context in comments.

Comments

0

Here is the simple code by abacus-common

Account account = N.fill(Account.class);
String xml = N.toXML(account);
N.println(xml); // <account><id>6264304841028291043</id><gui>33acdcbe-fd5b-49</gui><emailAddress>19c1400a-97ae-43</emailAddress><firstName>67922557-8bb4-47</firstName><middleName>7ef242c9-8ddf-48</middleName><lastName>1ec6c731-a3fd-42</lastName><birthDate>1480444055841</birthDate><status>1444930636</status><lastUpdateTime>1480444055841</lastUpdateTime><createTime>1480444055841</createTime></account>
Account account2 = N.fromXML(Account.class, xml);
assertEquals(account, account2);

Declaration: I'm the developer of abacus-common.

3 Comments

Care to elaborate?
Simplicity: It's easy to serialize an java Object to String/File/OuputStream/Writer or deserialize from String/File/InputStream/Reader. please refer to the Java API docs Parser[landawn.com/api-docs/com/landawn/abacus/parser/Parser.html]: in above
Performance: it's about 3 to 10+ times faster than JAXB provided in JDK and XStream, depending on the size of xml/Java Object. and about 20% faster thank Jackson XML. i will update the comments about performance in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.