Simple XML allows you to make your own converter.
This write method is used to serialize an object to XML. The serialization should be performed in such a way that all of the objects values are represented by an element or attribute of the provided node. This ensures that it can be fully deserialized at a later time.
@Convert(MyClass.Converter.class)
public class MyClass {
public MyClass() {}
public static class Converter implements Converter<MyClass> {
public MyClass read(InputNode node) {
return new MyClass();
}
public void write(OutputNode node, MyClass value) {
}
}
}
The documentation describes representing an element in the OutputNode, so how do you add an element to the OutputNode? The documentation for OutputNode doesn't appear to have any methods to add an element or node to it.
You can either add elements by hand or use another Serializer to add it -- Serializer also can write/read to/from nodes.
Here's an example:
@Root(name = "MyClass") // @Root required
@Convert(MyClass.MyClassConverter.class)
public class MyClass
{
private int value;
private String name;
/* Ctor, getter, setter etc. */
public static class MyClassConverter implements Converter<MyClass>
{
@Override
public MyClass read(InputNode node) throws Exception
{
MyClass mc = new MyClass();
/* Read the (int) value of 'someValue' node */
int value = Integer.parseInt(node.getNext("someValue").getValue());
mc.setValue(value);
/* Same for the string */
String name = node.getNext("someString_" + value).getValue();
mc.setName(name);
/* Do something with data not used in MyClass, but useable anyway */
if( node.getNext("from") == null )
{
throw new IllegalArgumentException("Node 'from' is missing!");
}
return mc;
}
@Override
public void write(OutputNode node, MyClass value) throws Exception
{
/* Add an attribute to the root node */
node.setAttribute("example", "true");
OutputNode valueNode = node.getChild("someValue"); // Create a child node ...
valueNode.setAttribute("stack", "overflow"); // ... with an attribute
valueNode.setValue(String.valueOf(value.getValue())); // ... and a value
/*
* Converter allow a dynamic creation -- here the node names is
* created from two values of MyClass
*/
node.getChild("someString_" + value.getValue()) // Create another child node ...
.setValue(value.getName()); // ... with a value only
/* Create another node from scratch */
OutputNode fromNode = node.getChild("from");
fromNode.setValue("scratch");
fromNode.setComment("This node is created by the converter");
}
}
}
The xml to write / read:
<MyClass example="true">
<someValue stack="overflow">27</someValue>
<someString_27>abc</someString_27>
<!-- This node is created by the converter -->
<from>scratch</from>
</MyClass>
Important: You have to use AnnotationStrategy, otherwise @Convert wont work.
Serializer ser = new Persister(new AnnotationStrategy())
ser.write(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With