Suzan Cioc
Suzan Cioc

Reputation: 30097

Create XML representaion of class instance from down to up?

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?

Upvotes: 1

Views: 193

Answers (1)

adarshr
adarshr

Reputation: 62563

Using XStream, I could do this:

package com.adarshr;

import com.thoughtworks.xstream.XStream;


class Parent {
    private String name;
    private int age;

    public Parent(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Test {
    private Parent parent = new Parent("Abcd", 30);

    public static void main(String[] args) throws Exception {
        System.out.println(new Test());
    }

    @Override
    public String toString() {
        return new XStream().toXML(this);
    }
}

Which prints:

<com.adarshr.Test>
  <parent>
    <name>Abcd</name>
    <age>30</age>
  </parent>
</com.adarshr.Test>

Of course, it is fully customisable.

Upvotes: 1

Related Questions