How can i generate xml from an object hierarchy?
-
05-07-2019 - |
Question
I have object, tree/model/hierarchy, whatever the correct term is. It consists of what could be characterized as a one-to-one mapping of the desired XML.
That is i have the following (in a non-standard UML sort of syntax)
class A {
class B b[*]
class C
class D
}
class B {
class C c[*]
string AttributeFoo = "bar"
}
class C {
string AttributeThis = "is"
}
class D {
string AttributeName = "d"
}
Desired output is something like this:
<?xml version="1.0"?>
<a>
<b attribute-foo="bar">
<c attribute-this="is"/>
</b>
<c attribute-this="is"/>
<d attribute-name="d"/>
</a>
What would you propose to be the best, and/or the simplest way of achieving this goal?
Solution
I would look at JAXB because a) you get it in the standard library and b) it isn't that complicated. This code requires Java 6:
@XmlRootElement public static class A {
public List<B> b = new ArrayList<B>();
}
public static class B {
public List<C> c = new ArrayList<C>();
@XmlAttribute(name = "attribute-foo") public String attributeFoo = "foo";
}
public static class C {
@XmlAttribute(name = "attribute-this") public String attributeThis = "is";
}
public static void main(String[] args) {
A a = new A();
a.b.add(new B());
a.b.get(0).c.add(new C());
JAXB.marshal(a, System.out);
}
//TODO: getters/setters, error handling and so on
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
<b attribute-foo="foo">
<c attribute-this="is"/>
</b>
</a>
OTHER TIPS
I think it is the purpose of JAXB (http://jaxb.java.net/) to map Objects to/from XML
If you want to use tools, have a look at jaxb. Marshalling/Unmarshalling is what your're doing here, it's a common problem with a lot of solutions available.
I think it's the best (not reinventing the wheel) and it's the simplest (I've done it manually and it's really no fun - object graphs can be cyclic...)
I like XMLBeans.
In my opinion if your not too bothered about performance I would stay away from Jaxb and take a look at some of the simpler frameworks. If performance is an issue I tend to favour jibx over jaxb for most situations.
In this situation I tend to use the simple project.
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#start
Just annotate your object model and away you go..... :-)
@Root
public class Example {
@Element
private String text;
@Attribute
private int index;
public Example() {
super();
}
public Example(String text, int index) {
this.text = text;
this.index = index;
}
public String getMessage() {
return text;
}
public int getId() {
return index;
}
}