views:

162

answers:

3

Let's say I have a class Foo with some primitive instance variables. I initialize these with properties in XML files. Now every Foo also has a Bar as a variable, which in turn has its own properties. Since these are tied to the enclosing object, it would make sense to keep them in the same file. How should I format the XML so that it can initialize the object as well?

+5  A: 

Use Spring. It's specifically designed to allow this type of object initialization, including handling inter-object references.

Vinay Sajip
+2  A: 

Take a look at XStream, which allows you to trivially serialise/deserialise a Java object hierarchy to/from XML.

At its simplest it'll work with a POJO, which no additional work (no interfaces/base classes etc. required). But you can customise how it serialises and deserialises to rename elements etc. to fit within an existing XML framework.

Brian Agnew
So far I like the idea of XStream, looking at their examples. However, I'm having the dreaded "content not allowed in prolog" exception.
pg-robban
Update: I managed to get it to work (I was stupid enough to read from a String and not a FileInputStream), not to mention my XML files look a lot prettier, too. I'm happy with this solution.
pg-robban
A: 

JAXB is worth a look:

public class JaxbDemo {

  @XmlRootElement
  public static class Foo {
    @XmlElement public Bar bar;
  }

  public static class Bar {
    @XmlAttribute public int baz;
  }

  public static void main(String[] args) {
    String xml = "<foo><bar baz='123'/></foo>";
    Foo foo = JAXB.unmarshal(new StringReader(xml), Foo.class);
    System.out.println(foo.bar.baz);
  }
}

(Public members used for demo purposes.)

McDowell