Search code examples
javaxmlapache-commons-digester

Digester rules for a string list


I have an xml doc that looks something like this:

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

My object looks like this:

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);
    }
}

I'm trying to map it like this:

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()));

However, I can't get it to populate the list. The total does get set correctly. For what it's worth, I have no control over the XML, but can change my Response object. Any ideas? Thanks in advance.


Solution

  • You have already had addWarning method in your Response class and warnings is initialized too. Just rewrite your rules:

        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);
    

    And that's all.