如何使用公共Digester解析xml文件并使其填充java.util.Date对象?

时间:2009-11-02 16:32:21

标签: java apache-commons-digester

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

样本消化器规则

<?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>

2 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分: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类中创建一个额外的setter:

public void setDobAsString(String dob) throws ParseException {
    setDob(parseDate(dob));
}