2016-10-06 1 views
0

Ich habe eine Klasse mit 10+ Parametern im Konstruktor und möchte ein Builder-Muster implementieren. Gleichzeitig möchte ich die einfache XML-Serialisierung verwenden, um Objekte aus XML-Dateien zu erstellen. Gibt es eine Möglichkeit, das zu erreichen?Einfache XML-Serialisierung + Builder-Muster

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; 
     [...] 
    } 

} 

Antwort

0

Aus meiner Sicht haben Sie keine bestimmte Wahl für eine XML-Bibliothek. Ich würde empfehlen, das Scilca XML Progression (SXP) -Paket zu verwenden, das bei GitHub verfügbar ist. Um einen Code für Objektserialisierung zu schreiben (wo Sie wissen, welches Objekt erzeugt werden soll), hier ist eine einfache Implementierung,

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 

     } 

}

+0

Nein, sorry, das; s nicht gültig, da ich das verwenden müssen Bibliothek, die ich erwähnt habe, und es sollte mir egal sein, wo die Objekte erstellt werden. –