commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig McClanahan" <craig...@apache.org>
Subject Re: [Digester] Converting String value of an attribute to array of integers
Date Sat, 18 Feb 2006 02:12:11 GMT
 2/17/06, Siddharth Mathur <smathur@nellymoser.com> wrote:
>
> Dear all,
>
> I am trying to use Digester to read my own XML format (shown below) and
> convert it to correctly initialized objects.
>
> <List>
>
> <A ID="1" author="Home made">
>         <range>90</range>
> </A>
>
> <B ID="2" author="Apple Inc." depends="1">
>         <bitrate>90</range>
> </B>
>
> [...more entries here]
>
> <C ID="7" author="CT" depends="4,6">
>         <flavour>AAC</range>
> </C>
>
> </List>
>
>
> Classes A, B, C are all derived from a parent class which has three
> properties:
> i) ID (integer)
> ii) author (String)
> iii) depends (array of IDs i.e integers)
>
> Digester makes it very easy to create setter and getter methods and read
> in
> (i) and (ii) above. But how do I modify the default Rule so that the
> String
> value of the "depends" attribute is converted to an array of integers
> property? I will be happy to reformat the depends="4,6" part if required.
>
> I currently use d.addSetProperties("List/A") to read in my other
> attributes.


As you might have figured out, you are going to need a new Rule
implementation to accomplish this.  Something along these lines should do
the trick (where MyClass is the bean class):

    public class DependsRule extends Rule {

        public DependsRule(Digester digester) {
            super(digester);
        }

        public void begin(String namespace, String name, Attributes
attributes) {
            // Peek at the object at the top of the stack
            MyClass bean = (MyClass) digester.peek();
            int depends[] = parse(attributes.getValue("dependsValue"); //
See note below
            bean.setDepends(depends);
        }

        private int[] parse(String value) {
            // Parse the incoming string into an array of int
            // and return it ...
        }

    }

Note that the above code assumes you change the attribute name from
"depends" to "dependsValue".  Alternatively, you could leave the attribute
name the same but change the property name on the bean to something else.
Making the names different is important to avoid having the Set Properties
Rule blow up because it doesn't know how to do this conversion.

To register this rule on your digester instance, you'd say:

    digester.addRule(new DependsRule(digester));


Thank you for your time and patience,
> Siddharth


Craig

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message