首页 > 解决方案 > simpleframework 转换元素

问题描述

我有下节课

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

我想为我的“值”使用转换器,因为它像字符串,但我需要它作为 BigDecimal。但是@Converter 或'Converter' 不适用于@Element,仅适用于@Attributes。

记录 XML 示例

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

RecordConverter 类是

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

但是,我不能在这里得到任何“名义”或“价值”。

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

标签: javaxmlsimple-framework

解决方案


虽然我自己从来没有使用过简单的 XML 序列化框架。InputNode但是看它的API,你可以自己遍历Converter 使用InputNode#getNext()or InputNode#getNext(String)

例如:

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类中设置,如下所示:

记录.java

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

推荐阅读