【问题标题】:Digester rules for a string list字符串列表的消化器规则
【发布时间】:2011-11-16 03:00:46
【问题描述】:

我有一个看起来像这样的 xml 文档:

<response>
  <total>1000</total>
  <warning>warning1</warning>
  <warning>warning2</warning>
</response>

我的对象如下所示:

public class Response {
    private BigDecimal total;

    private List<String> warnings=new ArrayList<String>();

    public List<String> getWarnings() {
        return warnings;
    }

    public void setWarnings(List<String> warnings) {
        this.warnings = warnings;
    }

    public BigDecimal getTotal() {
        return total;
    }

    public void setTotal(BigDecimal total) {
        this.total = total;
    }

    public void addWarning(String warning) {
        warnings.add(warning);
    }
}

我正在尝试像这样映射它:

Digester digester = new Digester();
digester.setValidating( false );
digester.addObjectCreate( "response", Response.class );
digester.addBeanPropertySetter( "response/total", "total" );
digester.addObjectCreate("response/warning","warnings", ArrayList.class);
digester.addCallMethod("response/warning", "add", 1);
digester.addCallParam("response/warning", 0);
ret = (Rate)digester.parse(new ByteArrayInputStream(xml.getBytes()));

但是,我无法让它填充列表。总数确实设置正确。对于它的价值,我无法控制 XML,但可以更改我的 Response 对象。有任何想法吗?提前致谢。

【问题讨论】:

    标签: java xml apache-commons-digester


    【解决方案1】:

    您的Response 类中已经有addWarning 方法,并且warnings 也已初始化。 只需重写你的规则:

        Digester digester = new Digester();
        digester.setValidating( false );
        digester.addObjectCreate("response", Response.class );
        digester.addBeanPropertySetter("response/total", "total" );
        digester.addCallMethod("response/warning", "addWarning", 1);
        digester.addCallParam("response/warning", 0);
    

    仅此而已。

    【讨论】:

      猜你喜欢
      • 2017-10-05
      • 2019-10-29
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      相关资源
      最近更新 更多