Posted on Nov 17, 2008

Generating xmlbeans from xml

This took me a while to figure out and I had to use many different sources so I figured I’d put the whole process here. The goal was to create xmlbeans for an API call that returned xml. I did not have an .xsd file to go by however, but xmlbeans comes with a couple of utilites that can be used to go from an instance of my API return to an xsd file, to xmlbeans. Here’s the process:

Generate an xsd file from your xml file using inst2xsd like so:

/opt/xmlbeans-2.4.0/bin/inst2xsd -outPrefix info.xsd info.xml

You should end up with a info0.xsd file. Take a look at this file to make sure the generic types look ok (string, short, float, etc). inst2xsd guesses at what they should be based on the content of the xml file but the xml file typically represents only one instance of the process.

Next, you can create the xmlbeans from the xsd file. To add a package name to the beans, you must create a file with an .xsdconfig extension in the same directory as your xsd file. Failing to do so will result in the default package name of ‘noNamespace’. The .xsdconfig file should look like this:

<xs:config xmlns:xs=”http://xml.apache.org/xmlbeans/2004/02/xbean/config”>
<!– Use the “namespace” element to map a namespace to the Java
package
name that should be generated. –>
<xs:namespace uri=”##any”>
<xs:package>com.bryandunn.project.mail</xs:package>
</xs:namespace>
</xs:config>

Next, run the xmlbeans utility scomp like so:

/opt/xmlbeans-2.4.0/bin/scomp -out info.jar info0.xsd info0.xsdconfig

This should result in an info.jar file with your xmlbeans which you can then reference like this:

import org.apache.xmlbeans.*;
import com.bryandunn.project.mail.*;
import java.io.*;

public class XMLBeanTest {

public static void main(String[] args) {

File xmlFile = new File("/home/bdunn/tmp/info.xml");

try {
    // Bind the instance to the generated XMLBeans types.
    MailClientDocument strDoc = MailClientDocument.Factory.parse(xmlFile);
    // Get and print pieces of the XML instance.
    MailClientType client = strDoc.getMailClient();
    MailingType mailing = client.getMailing();
    System.out.println(mailing.getConfigFile());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}