SimpleXMLConverter解析xml节点

时间:2017-02-14 11:34:22

标签: java xml simple-framework

我被困住了。如何使用同名子节点解析Node? 在这个例子中,我需要具有rate属性的节点。

<xml>
<Rates>
  <Rates winrate_cap="9999">
    <Rates rate="323"/>
    <Rates rate="343"/>
    <Rates rate="2338"/>
    <Rates rate="233"/>
  </Rates>
</Rates>
</xml>

我的回复包装类:

@Root(name = "xml", strict = false)
public class XMLResponse {

    @ElementList(entry = "Rates")
    public List<Rates> response;

    public static class Rates {

        @Attribute(name = "winrate_cap", required = false)
        public String winrate_cup;

        @ElementList(required = false, entry = "Rates")
        public List<Rates> rates;
    }

    public static class Rates {
        @Attribute(name = "rate", required = false)
        public String rate;
    }
}

1 个答案:

答案 0 :(得分:0)

你是正确的方式。由于这里有很多比率,因此可以通过更多上下文更好地命名类,并通过注释设置xml名称。

我已将XMLResponseRates类分开,但这并没有任何区别。

课程XMLRespone映射<xml>...</xml>部分:

@Root(name = "xml")
public class XMLRespone
{
    @Element(name = "Rates")
    private Rates rates;

    // ...
}

<Rates...>...</Rates>的所有类型都由Rates类完成(以及它的内部类,它们映射结构:

@Root(name = "Rates")
public class Rates
{
    @Element(name = "Rates")
    private RateList rates;

    // ...


    public static class RateList
    {
        @ElementList(entry = "Rates", inline = true)
        private ArrayList<RateValue> values;
        @Attribute(name = "winrate_cap", required = true)
        private int winrateCap;

        // ...
    }


    public static class RateValue
    {
        @Attribute(name = "rate", required = true)
        private int rate;

        // ...
    }

}

反序列化XML会产生此输出(使用生成的toString()):

XMLRespone{rates=Rates{rates=RateList{values=[RateValue{rate=323}, RateValue{rate=343}, RateValue{rate=2338}, RateValue{rate=233}], winrateCap=9999}}}