Introduction to XmlSemantics

XMLSemantics pays no attention to XML schemas. It uses simple reflection to determine what parts of an XML file are of interest, and ignores anything else. It treats attributes and nested simple values the same.

Example with attributes

Assume that you have the following trivial XML:

            <example quantity1="value1" quantity2="2" when="May 17, 2012"/>

To interpret it, we'll define a public class

            public class Example {
                private String quantity1;
                private int quantity2;
                private Date when;

                public setQuantity1(String quantity1) { this.quantity1 = quantity1; }
                public setQuantity2(int quantity2) { this.quantity2 = quantity2; }
                public setWhen(Date when) { this.when = when; }

                public String getQuantity1() { return quantity1; }
                public int getQuantity2() { return quantity2; }
                public Date getWhen() { return when; }
            }

And then use XMLSemantics to populate it as follows:

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

This has the effect of populating the fields in the returned object with the corresponding attribute values.

Example with simple elements

You would get the exact same effect if the XML were defined as:

            <example>
                <quantity1>value1</quantity1>
                <quantity2>2</quantity2>
                <when>5/17/2012</when>
            </example>

We use exactly the same code. XMLSemantics is happy to read either attributes or simple nested elements and treat them the same. In either case, it expects to find a public setter whose name matches the attribute name, and does whatever type conversion is appropriate to invoke it.