I was thinking to write a method in toString() like fashion so that it return XML representation of the class instance.
First I was thinking to write it like
public Element toElement() {
// create Element instance and fill it
}
But I was unable to create empty Element instance inside, since Element creation requires Document instance to call it’s createElement().
So I rewrote method to
public Element toElement(Document doc) {
Element ans = doc.createElement("myclasstag");
// filling ans
return ans;
}
But then I got runtime exception HIERARCHY_REQUEST_ERR since one can’t fill Element instance until it is attached to parent hierarchy.
So I was to rewrite method as follows
public Element toElement(Document doc, Element parent) {
Element ans = doc.createElement("myclasstag");
parent.appendChild(ans);
// filling ans
return ans;
}
But this way I need not return ans since it is already attached where it should be, so it became
public void append(Document doc, Element parent) {
Element ans = doc.createElement("myclasstag");
parent.appendChild(ans);
// filling ans
}
which is now absolutely dislike toString().
Is it possible to create XML instance from down to up fashion like toString() does?
Using XStream, I could do this:
Which prints:
Of course, it is fully customisable.