Search code examples
javaxmlsimple-framework

SimpleXML Single Depth Element with Attribute in Inline List


I want to parse the following XML

<entry key="9" type="9">
  <value>
    <amount stake="10">50000000</amount>
    <amount stake="1">5000000</amount>
    <winner>0.0</winner>
    <description>9 Correct Numbers</description>
  </value>
</entry>

I try to achieve this with the follow classes:

@Root(name="entry")
public class OddsEntryXMLObject {

    @Attribute(name="key")
    private String iKey;

    @Attribute(name="jackpot", required=false)
    private String iJackpot;

    @Attribute(name="type", required=false)
    private String iType;

    @Element(name="value")
    private OddsValueXMLObject iOddsValueXMLObject;
}

public class OddsAmountXMLObject {

    @Element(name="amount")
    private String iAmount;

    @Attribute(name="stake", required=false)
    private String iStake;
}

However I get the following exception:

java.lang.RuntimeException: org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy @org.simpleframework.xml.Element(data=false, name=amount, required=true, type=void) on field 'iAmount' private java.lang.String OddsAmountXMLObject.iAmount for class OddsAmountXMLObject at line 1

Anyone know how to parse this?


Solution

  • There is no declaration for OddsValueXMLObject class in the code provided. Assuming the declaration is what I think it is, the error message basically means that it expects an amount element inside an amount element, like this:

    <amount>
        <amount></amount>
    </amount>
    

    Of course, there is nothing like that in the XML you have. You can parse it with this instead:

    @Root(name="entry")
    public class OddsEntryXMLObject{
        @Attribute(name="key")
        private String key;
    
        @Attribute(name="jackpot", required=false)
        private String jackpot;
    
        @Attribute(name="type", required=false)
        private String type;
    
        @Element(name="value")
        private OddsValueXMLObject value;
    }
    
    @Root(name="value")
    public class OddsValueXMLObject{
        @ElementList(inline=true)
        private java.util.List<OddsAmountXMLObject> amounts;
    
        @Element(name="winner", required=false)
        private String winner;
    
        @Element(name="description", required=false)
        private String description;
    }
    
    @Root(name="amount")
    public class OddsAmountXMLObject{
        @Attribute(name="stake", required=false)
        private String stake; 
    
        @Text
        private String text;
    }