1

我有以下 XML 结构:

<key>
   <element>
      someValue
   </element>

   <!-- lots of other elements which should be deserialized into the class -->

   <other>
      someOtherValue
   </other>
</key>

我使用Simple将其反序列化为以下 Java 类:

@Root(name = "key", strict = false)
public class Key {

    @Element(name = "element")
    private String element;

    // lots of more fields should be deserialized from xml
}

请注意,该类没有other元素的字段。我不需要它在课堂上的价值,而是在其他地方。如何拦截解析并提取该other元素的值?

4

3 回答 3

0

我无法按照ngKatona的建议使用Stragegyor解决方案。但是,我做了一个解决方法,它有效,但不太好。Converter

/* package */ class SerializedKey extends Key {

    @Element(name = "other", required = false)
    private int mOtherValue;

    public int getOtherValue() {
        return mOtherValue;
    }
}

...

Serializer serializer = new Persister();
SerializedKey key = serializer.read(SerializedKey.class, mInputStream);
int otherValue = key.getOtherValue();

在序列化包之外,我Key用作静态类型,所以我只是忘记了另一个字段在该对象中。当我坚持我的数据时,我也坚持为Key,所以mOtherValue不再连接到班级。如您所见SerializedKey,类是包私有的,因此我不会将此帮助程序类公开给我的应用程序的任何其他组件。

于 2013-08-08T21:54:17.807 回答
0

您可以通过多种方式做到这一点,最好是使用转换器策略。转换器是两者中最简单的。

于 2013-08-06T15:16:36.013 回答
0

我认为这种Strategy方法行不通,因为他们使用带注释的类作为 XML 架构,而架构中不存在的内容将不会被处理(访问者无法访问)。

转换器可以按如下方式使用:

@Root(name = "key", strict = false)
@Convert(KeyConverter.class)
public class Key {

    private String element;

    public Key(String elementValue) {
        element = elementValue;
    }

}

转换器在转换期间存储值:

public class KeyConverter implements Converter<Key> {

    private String otherValue;

    @Override
    public Key read(InputNode node) throws Exception {
        String elementValue = node.getNext("element").getValue().trim();
        otherValue = node.getNext("other").getValue().trim();
        return new Key(elementValue);
    }

    @Override
    public void write(OutputNode arg0, Key arg1) throws Exception {
        throw new UnsupportedOperationException();
    }

    /**
     * @return the otherValue
     */
    public String getOtherValue() {
        return otherValue;
    }

}

放在一起:

    Registry registry = new Registry();

    KeyConverter keyConverter = new KeyConverter();
    registry.bind(Key.class, keyConverter);

    Persister serializer = new Persister(new RegistryStrategy(registry));
    Key key = serializer.read(Key.class, this.getClass().getResourceAsStream("key.xml"));
    // Returns the value "acquired" during the last conversion
    System.out.println(keyConverter.getOtherValue());

这不是太优雅,但可能适合您的需要。

于 2013-08-06T15:42:53.200 回答