我认为这种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());
这不是太优雅,但可能适合您的需要。