van*_*rra 3 java xml-parsing simple-framework
简单的XML允许您制作自己的转换器.
此write方法用于将对象序列化为XML.应该以这样的方式执行序列化:所有对象值由所提供节点的元素或属性表示.这确保了它可以在以后完全反序列化.
@Convert(MyClass.Converter.class)
public class MyClass {
public MyClass() {}
public static class Converter implements Converter<MyClass> {
public MyClass read(InputNode node) {
return new MyClass();
}
public void write(OutputNode node, MyClass value) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
该文档描述了在OutputNode中表示元素,那么如何向OutputNode添加元素?OutputNode的文档似乎没有任何方法可以向其添加元素或节点.
您既可以手动添加元素,Serializer也可以使用其他元素添加元素- Serializer也可以向/从节点写入/读取.
这是一个例子:
@Root(name = "MyClass") // @Root required
@Convert(MyClass.MyClassConverter.class)
public class MyClass
{
private int value;
private String name;
/* Ctor, getter, setter etc. */
public static class MyClassConverter implements Converter<MyClass>
{
@Override
public MyClass read(InputNode node) throws Exception
{
MyClass mc = new MyClass();
/* Read the (int) value of 'someValue' node */
int value = Integer.parseInt(node.getNext("someValue").getValue());
mc.setValue(value);
/* Same for the string */
String name = node.getNext("someString_" + value).getValue();
mc.setName(name);
/* Do something with data not used in MyClass, but useable anyway */
if( node.getNext("from") == null )
{
throw new IllegalArgumentException("Node 'from' is missing!");
}
return mc;
}
@Override
public void write(OutputNode node, MyClass value) throws Exception
{
/* Add an attribute to the root node */
node.setAttribute("example", "true");
OutputNode valueNode = node.getChild("someValue"); // Create a child node ...
valueNode.setAttribute("stack", "overflow"); // ... with an attribute
valueNode.setValue(String.valueOf(value.getValue())); // ... and a value
/*
* Converter allow a dynamic creation -- here the node names is
* created from two values of MyClass
*/
node.getChild("someString_" + value.getValue()) // Create another child node ...
.setValue(value.getName()); // ... with a value only
/* Create another node from scratch */
OutputNode fromNode = node.getChild("from");
fromNode.setValue("scratch");
fromNode.setComment("This node is created by the converter");
}
}
}
Run Code Online (Sandbox Code Playgroud)
要写/读的xml:
<MyClass example="true">
<someValue stack="overflow">27</someValue>
<someString_27>abc</someString_27>
<!-- This node is created by the converter -->
<from>scratch</from>
</MyClass>
Run Code Online (Sandbox Code Playgroud)
重要提示:您必须使用AnnotationStrategy,否则将@Convert无法工作.
Serializer ser = new Persister(new AnnotationStrategy())
ser.write(...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1750 次 |
| 最近记录: |