2.9. Configuring Fixed-Length Records

  1. To bind fixed-length records to a person, see the configuration below. In this example we will use these sample records:
    Tom Fennelly   M 21 IE
    Maurice Zeijen M 27 NL
    
    This is how you bind them to a person:
    public class Person {
        private String firstname;
        private String lastname;
        private String country;
        private String gender;
        private int age;
    }
  2. Configure the records so they look like this:
    <?xml version="1.0"?>
    <smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"  xmlns:fl="http://www.milyn.org/xsd/smooks/fixed-length-1.3.xsd">
     
        <fl:reader fields="firstname[10]?trim,lastname[10]?trim,gender[1],age[3]?trim,country[2]">
            <!-- Note how the field names match the property names on the Person class. -->
            <fl:listBinding BeanId="people" class="org.milyn.fixedlength.Person" />
        </fl:reader>
     
    </smooks-resource-list>
  3. Execute it as shown:
    Smooks smooks = new Smooks(configStream);
    JavaResult result = new JavaResult();
     
    smooks.filterSource(new StreamSource(fixedLengthStream), result);
     
    List<Person> people = (List<Person>) result.getBean("people");
  4. Optionally, use this configuration to create maps from the fixed-length record set:
    <?xml version="1.0"?>
    <smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"  xmlns:fl="http://www.milyn.org/xsd/smooks/fixed-length-1.3.xsd">
     
        <fl:reader fields="firstname[10]?trim,lastname[10]?trim,gender[1],age[3]?trim,country[2]">
            <fl:mapBinding BeanId="people" class="org.milyn.fixedlength.Person" keyField="firstname" />
        </fl:reader>
            
    </smooks-resource-list>
  5. This is how you execute the map of person instances that is produced:
    Smooks smooks = new Smooks(configStream);
    JavaResult result = new JavaResult();
     
    smooks.filterSource(new StreamSource(fixedLengthStream), result);
     
    Map<String, Person> people = (Map<String, Person>) result.getBean("people");
     
    Person tom = people.get("Tom");
    Person mike = people.get("Maurice");
    Virtual Models are also supported, so you can define the class attribute as a java.util.Map and bind the fixed-length field values to map instances, which are in turn added to a list or a map.