Search code examples
javaapache-commons-digester

Using commons digester how do I parse a single xml entry into multiple fields in an object?


How do I map "Joe Smith" to first name "Joe" last name "Smith"?

I already have code to split up the name, I'm not sure how to make that work with the Digester though.

<guestlist>
  <guest>
   <name>Joe Smith</name>
  </guest>
</guestlist>

public class Guest(){
  private String firstName;
  private String lastName;
...
}

Solution

  • An easy answer is: add an additional property to your Guest class:

    public class Guest {
        private String firstName;
        private String lastName;
        public void setBothNames(String bothNames) {
            String[] split = bothNames.split(" ");
            firstName = split[0];
            lastName = split[1];
        }
    

    and the bean property setter rule to the digester:

        digester.addBeanPropertySetter("guestlist/guest/name", "bothNames");