Person fred = new Person(101, "Fred", "Feuerstein", "ff@email.com");
try {
// Get an ObjectTransformer.
// The ObjectTransformer interface offers all needed methods.
ObjectTransformer trans =
ObjectTransformerFactory.getInstance().getImplementation();
// The transformer should create extra line feeds in the output.
trans.setProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
// Set the amount of indenting if Xalan is used as XSL transformer.
trans.setProperty("{http://xml.apache.org/xalan}indent-amount", "2");
// Use western european encoding in the XML output.
//trans.setProperty(javax.xml.transform.OutputKeys.ENCODING, "ISO-8859-1");
// Serialize the Person object into a file.
FileOutputStream out = new FileOutputStream("fred.xml");
trans.serialize(fred, new StreamResult(out));
out.close();
// Create an XML schema file that describes the Person class.
out = new FileOutputStream("Person.xsd");
trans.writeXMLSchema(Person.class, new StreamResult(out));
out.close();
// Read a Person's XML file and create a new Person object
// from its content.
FileInputStream in = new FileInputStream("fred.xml");
Person freddy = (Person) trans.deserialize(new StreamSource(in));
in.close();
// Check the result.
if (fred.equals(freddy)) {
System.out.println("OK");
}
else {
System.out.println("ERROR");
}
// Demonstrate the setting of properties for the serializer
trans.setProperty(com.skaringa.javaxml.PropertyKeys.OMIT_XSI_NIL, "true");
trans.setProperty(
com.skaringa.javaxml.PropertyKeys.OMIT_XSI_TYPE,
"true");
trans.setProperty(com.skaringa.javaxml.PropertyKeys.OMIT_ID, "true");
// Serialize the Person object into a file.
// Omit all xsi:type, xsi:nil and id attributes.
// This will shorten the output and make it more "human readable",
// but this may not work correctly for all kinds of objects.
out = new FileOutputStream("fred_short.xml");
trans.serialize(fred, new StreamResult(out));
out.close();
// ... and deserialize it again
// Note that the transformer used for deserialization also needs
// the property OMIT_XSI_TYPE
in = new FileInputStream("fred_short.xml");
Person freddyboy = (Person) trans.deserialize(new StreamSource(in));
in.close();
// Check the result.
if (fred.equals(freddyboy)) {
System.out.println("OK again");
}
else {
System.out.println("ERROR 2");
}
// Demonstrate the Java object transformation
// Create an XML schema file that describes the OrgMember class.
out = new FileOutputStream("OrgMember.xsd");
trans.writeXMLSchema(OrgMember.class, new StreamResult(out));
out.close();
// set the transformation stylesheet
trans.setPostprocessorInstruction(
new StreamSource(
ClassLoader.getSystemResourceAsStream(
"com/skaringa/javaxml/example/Person2OrgMember.xsl")));
// transform using the previously set (and pre-parsed) stylesheet
OrgMember fredTheMember = (OrgMember) trans.transform(fred);
System.out.println(fredTheMember);
}
// Handle the weird things...
catch (NoImplementationException e) {