Download : http://xstream.codehaus.org/download.html
XML Serialization is essential in some situations. Most probably we may use XML serialization when we need higher level of portability. XStream is a great library for xml serialization.
Serializing
import com.thoughtworks.xstream.XStream; import model.TestCase; import model.TestStep; import model.TestSuite; public class XStreamSerializeDemo { /** * @param args */ public static void main(String[] args) { TestStep tstp1=new TestStep(); tstp1.setId(1); tstp1.setName("Enter unamex on username"); TestStep tstp2=new TestStep(); tstp2.setId(1); tstp2.setName("Enter passwd on password"); TestStep tstp3=new TestStep(); tstp3.setId(1); tstp3.setName("Click on login button"); TestCase tc=new TestCase(); tc.setName("User Login"); tc.getTestSteps().add(tstp1); tc.getTestSteps().add(tstp2); tc.getTestSteps().add(tstp3); TestCase tc1=new TestCase(); tc1.setName("Fill dummy Vals"); tc1.getTestSteps().add(tstp1); tc1.getTestSteps().add(tstp2); TestSuite ts=new TestSuite(); ts.setName("Test Suite 1"); ts.getTestCases().add(tc); ts.getTestCases().add(tc1); //initializing the serializer XStream xstream=new XStream(); //mapping part *not essential xstream.alias("testcase", TestCase.class); xstream.alias("teststep", TestStep.class); xstream.alias("testsuite", TestSuite.class); String xml=xstream.toXML(ts); System.out.println(xml); } }
Deserializing
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import model.TestCase; import model.TestStep; import model.TestSuite; import com.thoughtworks.xstream.XStream; public class XStreamDeserializeDemo { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { XStream xstream=new XStream(); //mapping part *not essential xstream.alias("testcase", TestCase.class); xstream.alias("teststep", TestStep.class); xstream.alias("testsuite", TestSuite.class); //TestSuite ts=(TestSuite) xstream.fromXML("xml string goes here"); FileInputStream fin=new FileInputStream(new File("C:\\Users\\kanishkad\\Desktop\\output.xml")); TestSuite ts=new TestSuite(); ts=(TestSuite) xstream.fromXML(fin,ts); System.out.println(ts.getTestCases().get(0).getTestSteps().get(0).getName()); } }
Serialized object :
<testsuite> <name>Test Suite 1</name> <testCases> <testcase> <name>User Login</name> <testSteps> <teststep> <name>Enter unamex on username</name> <id>1</id> </teststep> <teststep> <name>Enter passwd on password</name> <id>1</id> </teststep> <teststep> <name>Click on login button</name> <id>1</id> </teststep> </testSteps> </testcase> <testcase> <name>Fill dummy Vals</name> <testSteps> <teststep reference="../../../testcase/testSteps/teststep"/> <teststep reference="../../../testcase/testSteps/teststep[2]"/> </testSteps> </testcase> </testCases> </testsuite>
0 comments:
Post a Comment