Presents your JAVA E-NEWSLETTER for November 25, 2002 <-------------------------------------------> NOTICE TO SUBSCRIBERS: Due to the Thanksgiving holiday, the Java newsletter will not be delivered on Thursday, Nov. 28, 2002. Look for your next edition of the Java TechMail on Monday, Dec. 2, 2002. ---------------------------------------- APPLY THE POWER OF XPATH TO JAVABEANS Asking a JavaBean for 'addressbook[1].state.code' is a common way of interacting with JavaBeans nowadays, but you can go a step further and use the more powerful XPath specification. XPath was created to access and modify data in XML, but a new project from the Apache Jakarta group allows you to apply the powerful XPath specification to ordinary JavaBeans. To provide an example, we'll use a JavaBean with the following structure: Person.name is a String Person.age is an int Person.birthtown is a Town Person.address is an array of Address Town.name is a String Address.number is a String Address.street is a String Address.town is a Town (The code isn't shown to maintain brevity.) Given a person object, you can get the object's name with "name"; you can get the name of birthtown with "birthtown/name"; and you can get the name of the town associated with an address (e.g., 21) with "address[number='21']/town/name". The main difference between XPath and typical bean notation, apart from being more powerful, is the use of '/' rather than '.' to separate elements. Once you get used to that aspect, it all becomes quite easy. The following code shows how simple it is to use JXPath to apply XPath notation to our JavaBean structure: import org.apache.commons.jxpath.JXPathContext; .... Person person = ....; JXPathContext context = JXPathContext.newContext(person); System.out.println(context.getValue("name")); System.out.println(context.getValue("age")); System.out.println(context.getValue("birthtown/name")); System.out.println(context.getValue("address[number='21']/street")); System.out.println(context.getValue("address[number='21']/town/name")); .... XPath can be used to set values and to create beans, as well as to get values. For more information on XPath and its JXPath implementation, see the JXPath Web site. http://jakarta.apache.org/commons/jxpath/ ----------------------------------------