ScArcher2
ScArcher2

Reputation: 87237

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;
...
}

Upvotes: 0

Views: 619

Answers (2)

mhaller
mhaller

Reputation: 14222

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");

Upvotes: 1

Rasik Jain
Rasik Jain

Reputation: 1086

// Loading from a file, you can also load from a stream
XDocument loaded = XDocument.Load(@"C:\Guests.xml");


// Query the data and write out a subset of guests

var guests= from c in loaded.Descendants("guest")
        select new
        {
            FirstName = SplitFunc_FirstName(c.Element("name")),
            LastName = SplitFunc_LastName(c.Element("name"))
        };

foreach (var guest in guests)
{
    Your custom code...to attach it to your entity object.
}

Note: SplitFunc_FirstName is your custom function which you already wrote to extact first and last name.

Upvotes: 0

Related Questions