You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by Lance Semmens <la...@essential.com.au> on 2004/11/23 03:59:21 UTC

[digester] Setting arbitrary XML attributes

I'm wanting to set all XML attributes on my object.
At the time of XML digesting, I don't know the set of attribute names.
If I use a SetPropertiesRule, my object will require a setX() method for
every attribute.

If I parse
	<mybean foo="ABC" bar="123" />

Using the following bean:
	public class MyBean {
		public Map attributes = new HashMap();
		public void setAttribute(String name, String value);
	}

I'd like the digester to do the following:
	MyBean myBean = new MyBean();
	myBean.setAttribute("foo", "ABC");
	myBean.setAttribute("bar", "123");

Is there a digester rule that will do this?

Thanks,
Lance.

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org


Re: [digester] Setting arbitrary XML attributes

Posted by Simon Kitching <si...@ecnetwork.co.nz>.
Hi Lance,

On Tue, 2004-11-23 at 15:59, Lance Semmens wrote:
> I'm wanting to set all XML attributes on my object.
> At the time of XML digesting, I don't know the set of attribute names.
> If I use a SetPropertiesRule, my object will require a setX() method for
> every attribute.
> 
> If I parse
> 	<mybean foo="ABC" bar="123" />
> 
> Using the following bean:
> 	public class MyBean {
> 		public Map attributes = new HashMap();
> 		public void setAttribute(String name, String value);
> 	}
> 
> I'd like the digester to do the following:
> 	MyBean myBean = new MyBean();
> 	myBean.setAttribute("foo", "ABC");
> 	myBean.setAttribute("bar", "123");
> 
> Is there a digester rule that will do this?

There's no standard Rule class distributed with Digester that does this,
but implementing your own subclass of Rule to do this is very easy.

Roughly:

public class MyBeanAttributeSetterRule 
   extends org.apache.commons.digester.Rule
 {
   public void begin(String namespace, String name, Attributes attrs)
   {
     MyBean b = (MyBean) digester.peek();
     for each attribute in attrs
       call setAttribute(name, value)
   }
 }

Then of course:
   digester.addRule(somePattern, new MyBeanAttributeSetterRule());
   ...

Of course it would be possible to use reflection etc to avoid direct
coupling between the new Rule class and the MyBean class, but there's
probably not much point.

Regards,

Simon


---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org