Dec 24

Showing off X2J I created the following XSD example, which is a simple definition for a contact list which can store connections between the contacts:


<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="contactList">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="contact" minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="friend-of" type="xs:string" minOccurs="0"
       maxOccurs="unbounded"/>
            </xs:sequence>
            
<xs:attribute name="name" type="xs:string" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:attribute name="owner" type="xs:string"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

You can see I’m using “friend-of” as a list of names. When an XML binding generator creates classes from this, it is likely to produce a String[] getFriendOfArray() or something similar.

Check out the corresponding X2J code:


01 @Element
02 public class Contact {
03   @Attribute
04   @PrimaryKey
05   String getName() {..}
06   
07   @InnerElement
08   @ArrayElement(label=false)
09   Contact[] getFriendOf() {..}
10 
11 }

Java2html

You can see how I can access the Contact instances who are friends with a certain Contact instance immediately; Also, when an XML conforming to this X2J annotated class is parsed, any contact on the “friend-of” list will be checked for existence as part of validation testing, something that (to my humble knowledge) just wouldn’t happen in a regular XSD generated class.

I’d love to hear comments, remarks, bashings, suggestions… Anything.

  • Share/Bookmark

3 Responses to “XML to POJOs Example – Contacts List”

  1. New project coming up at Chaotic Java Says:

    [...] No, I haven’t put X2J aside. I can tell you that in just a few minutes I will open up IDEA and the X2J project and continue writing some code into it. Hopefully a release will be out soon for all of you to download (Even more hopefully you will actually download it..) [...]

  2. XML Binding Framework Beta-1 Released at Chaotic Java Says:

    [...] Primary Keys Discussed it thoroughly here, and generally they provide for a way to reuse serialized items, thus making an XML document substantially smaller, and re-creating the parsed object tree to be exactly as it was before serialization. [...]

  3. Some thoughts about Java EE 5 at Chaotic Java Says:

    [...] As for JAXB… I can only say I don’t like XSDs and specifically crafted classes that the JAXB framework generates, and my intention is of using annotations to replace the need for them in closed-applications, and to generate them on demand for b2b applications, by creating my own framework for XML binding, currently code-named X2J (First beta is already available!) [...]

Leave a Reply

Chaotic Java is Digg proof thanks to caching by WP Super Cache