1

示例 XML。

<person>
  <name>Joe Dirt</name>
  <ssn>123-45-6789</ssn>
  <dob>07/04/1981</dob>
</person>

示例 Java 类

public class Person(){
  private String name;
  private String ssn;
  private java.util.Date dob;
.....
}

示例 Digester 规则

<?xml version="1.0"?>
<digester-rules>
  <pattern value="message">
      <object-create-rule classname="Person" />
      <bean-property-setter-rule pattern="name" propertyname="name" />
      <bean-property-setter-rule pattern="ssn" propertyname="ssn" />
      <bean-property-setter-rule pattern="dob" propertyname="dob" />
 </pattern>
</digester-rules>
4

2 回答 2

6

应该能够注册一个 DateConverter,并且一切都应该工作:

import org.apache.commons.beanutils.Converter;

class MyDateConverter implements Converter {
    @Override
    public Object convert(Class clazz, Object value) {
        if (clazz.equals(Date.class)) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            try {
                return sdf.parse((String) value);
            } catch (ParseException pe) {
                throw new IllegalArgumentException(pe);
            } catch (ClassCastException cce) {
                throw new IllegalArgumentException(cce);
            }
        } else {
            throw new IllegalArgumentException("Expected Date class");
        }
    }
}

......

import org.apache.commons.beanutils.ConvertUtils;

@Test
public void testXmlRules() throws Exception {
    ConvertUtils.register(new MyDateConverter(), Date.class);
    Digester digester = DigesterLoader.createDigester(new InputSource(this
            .getClass().getResourceAsStream("rules.xml")));
    Person person = (Person) digester.parse(this.getClass()
            .getResourceAsStream("person.xml"));
    Assert.assertEquals("Joe Dirt", person.getName());
    Assert.assertEquals("123-45-6789", person.getSsn());
    Assert.assertEquals(new SimpleDateFormat("dd/MM/yyyy")
            .parse("07/04/1981"), person.getDob());
}
于 2009-11-02T18:01:24.880 回答
1

我自己曾经遇到过这个问题。我没有找到任何标准的方法来做到这一点。我想出的最好的是:

digester.addRule(ROOT + "/lastBuildDate", new Rule() {
  public void body(final String namespace, final String name, final String text) throws Exception {
    Message message = (Message) getDigester().peek();
    if (text == null || text.trim().equals("")) {
      message.setDate(new Date());
    } else {
      try {
        message.setDate(parseDate(text));
      } catch (final ParseException e) {
        Log.warn("failed to parse date: " + text, e);
        message.setDate(new Date());
      }
    }
  }
});

Date parseDate(String text) throws ParseException {
  // left as an exercise to the reader
}

我无法使用来自您的消化器 XML 的自定义规则,因为我一直更喜欢以编程方式构建消化器。

作为一种解决方法,您可以在您的 Person 类中创建一个额外的设置器:

public void setDobAsString(String dob) throws ParseException {
    setDob(parseDate(dob));
}
于 2009-11-02T16:48:15.607 回答