简单框架转换元素

simpleframework convert element

我有下一个class

@Root
@Convert(RecordConverter.class)
public class Record {
    public static final String DATE = "Date";
    public static final String ID = "Id";
    public static final String NOMINAL = "Nominal";
    public static final String VALUE = "Value";

    @Attribute(name = DATE)
    String date;
    @Attribute(name = ID)
    String id;
    @Element(name = NOMINAL)
    int nominal;
    @Element(name = VALUE)
    String value;
}

我想为我的 'Value' 使用转换器,因为它类似于 String,但我需要它作为 BigDecimal。但@Converter 或 'Converter' 不适用于 @Element,仅适用于 @Attributes。

记录示例XML

<Record Date="05.03.2020" Id="R01235">
    <Nominal>1</Nominal>
    <Value>66,0784</Value>
</Record>

RecordConverter class 是

public class RecordConverter implements Converter<Record> {
    Record record;

    public Record read(InputNode node) throws Exception {
        record = new Record();
        record.setDate(node.getAttribute(DATE).getValue());
        record.setId(node.getAttribute(ID).getValue());
        if (node.getAttribute(NOMINAL) != null) {
            record.setNominal(Integer.parseInt(node.getAttribute(NOMINAL).getValue()));
        } else {
            record.setNominal(1);
        }
        if (node.getAttribute(VALUE) != null) {
            record.setValue(node.getAttribute(VALUE).getValue());
        } else {
            record.setValue("qw");
        }
        return record;
    }

    public void write(OutputNode node, Record value) throws Exception {
        throw new UnsupportedOperationException("Not ready converter yet");
    }
}

但是,我在这里找不到任何 'Nominal' 或 'Value'。

我的问题是如何将我的值从字符串 66,0784 转换为 BigDecimal 66.0784?

虽然我自己从来没有用过SimpleXML序列化框架。 但是看它的API,你可以在Converter中用InputNode#getNext()或者InputNode#getNext(String).

自己遍历InputNode

例如:

public Record read(InputNode node) throws Exception {
    final Record record = new Record();
    record.setDate(node.getAttribute(DATE).getValue());
    record.setId(node.getAttribute(ID).getValue());

    // Default values
    record.setNominal(1);
    record.setValue(BigDecimal.ONE);

    for (InputNode next = node.getNext(); next != null; next = node.getNext()) {
        switch (next.getName()) {
            case NOMINAL:
                record.setNominal(Integer.parseInt(next.getValue()));
                break;
            case VALUE:
                record.setValue(new BigDecimal(next.getValue()));
                break;
        }
    }
    return record;
}

注意,默认值也可以直接在模型中设置 Record class,像这样:

Record.java

    ...
    @Element(name = NOMINAL)
    int nominal = 1;
    @Element(name = VALUE)
    BigDecimal value = BigDecimal.ONE;
    ...