我在构造函数中有一个带有10+参数的类,我想实现一个生成器模式。同时,我希望使用简单的XML序列化从XML文件构建对象。有什么方法可以做到这一点吗?
import org.simpleframework.xml.*;
public class Example {
@Element(name = "field-1", required = false)
private final int field1;
@Element(name = "field-2")
private final int field2;
[...]
public simpleXMLConstructor(
@Element(name = "field-1", required = false) int field1,
@Element(name = "field-2") int field2,
[...]) {
this.field1 = field1;
this.field2 = field2;
[...]
}
}发布于 2016-10-09 13:30:07
据我所知,对于任何XML库,您都没有任何特定的选择。我推荐使用GitHub上提供的Scilca XML Progression (SXP)包。为了编写对象序列化的代码(您知道要创建哪个对象),下面是一个简单的实现,
import org.scilca.sxp.*;
import org.scilca.sxp.exceptions.*;
public class main{
class XmlSerialization{.....} // We'll serialize this and
class XmlS2 {}
public static void main(String[] args){
// Write Data
Node rootNode = new XMLNode("ObjectSerializationData");
XMLNode firstObject = rootNode.add("XmlSerialization");
firstObject.add("IntField1").setValue("1");
firstObject.add("StringField2").setValue("strObject");
XMLNode secondObject = rootNode.add("XmlS2");
secondObject.add("IntField1").setValue("2"); // Added a element with a value
secondObject.add("BoolField2").setValue("false");
XMLNode thirdObject = rootNode.add("XmlSerialization");
thirdObject.add("IntField1").setValue("@null");
thirdObject.add("StringField2").setValue("str");
Document XmlDocument = new Document(rootNode);
Writer w = (Writer) XmlDocument.getWriter();
w.saveXML("D:/file.txt");
System.gc();
// Read and Deserialize
XMLReader xr = new XMLReader("D:/file.txt");
Document newXml = xr.parseDocument();
List<Node> XmlS1Nodes = newXml.searchMatches("XmlSerialization");
List<Node> XmlS2Nodes = newXml.searchMatches("XmlS2");
Node firstObject = XmlS1Nodes.get(0);
int field1 = (int) Double.parseDouble(firstObject.getAllChildren().get(0));
// Like this get all field and construct objects
}}
https://stackoverflow.com/questions/39893412
复制相似问题