Java Reference
In-Depth Information
// We save their preferences
// Configuration c = ... - set above
Writer saveFile
=
new
new
FileWriter
(
f
);
saver
.
marshal
(
c
,
saveFile
);
saveFile
.
close
();
// Confirm that the XML file got written
assertTrue
(
f
.
exists
());
System
.
out
.
println
(
"JAXB output saved in "
+
f
.
getAbsolutePath
());
// Sometime later, we read it back in.
Unmarshaller loader
=
jc
.
createUnmarshaller
();
Configuration c2
= (
Configuration
)
loader
.
unmarshal
(
f
);
// Outside of the simulation, we test that what we
// read back is the same as what we started with.
assertEquals
(
"saved and loaded back the object"
,
c
,
c2
);
After the test runs, the
config.save
file is left in the testing directory; I grabbed a copy of this,
reformatted it, and saved it in the source directory with
.xml
appended to the filename. The
content looks as you'd expect:
<config>
<screenName>
<screenName>
idarwin
</screenName>
</screenName>
<verbose>
<verbose>
true
</verbose>
</verbose>
<colorName>
<colorName>
inky green
</colorName>
</colorName>
</config>
Converting Between Objects and XML with Serializers
Problem
You want to generate XML directly from Java objects, or vice versa.
Solution
Another way is to use the XML Object Serializers.