Handling Nested Elements

To handle more complex xml, we use create methods to instantiate nested objects. For example:

            <example>
                <oil-paint color="red"/>
                <oil-paint color="green"/>
            <example/>

Here, the oil-paint element itself has attributes, so cannot be treated as a simple value. When encountering a nested element, the build method looks for a method on the current object named createXXX, where XXX is the name of the element. An element name containing hyphens is interpreting as the equivalent camel case name. So in this case, we create the following classes:

            public class Example {
                private List<OilPaint> paints = new ArrayList<>();

                public Paint createOilPaint() {
                    Paint paint = new OilPaint();
                    paints.add(paint);
                    return paint;
                }

                public Paint[] getPaints() {
                    return paints.toArray(new Paint[paints.size()]);
                }
            }

            public class Paint {
                private String color;

                public void setColor(String color) { this.color = color; }
                public String getColor() { return color; }
            }

Again, we populate the objects with:

        Document dom = XMLSemantics.parseDocument(new File("example.xml"));
        Example example = XMLSemantics.build(dom, new Example(), "example.xml");
    

In this case, when it encounters the <oil-paint> element, the build method looks for a method named createOilPaint in Example. It calls that and receives a Paint object. When it encounters the color attribute, it calls the setColor method in Paint.

If oil-paint itself had a nested element, the code would look for a matching createXXX element on Paint, and so on. If a setXXX method is found instead, its text contents are used to establish a value for the corresponding attribute.