很方便,很容易,很快,心情很愉快:)
对象转String,String转对象.对象转文件,文件转对象.
/** * 对象转文件,文件转回对象 */ @Test public void testFromFile() throws IOException { String fileName = "d:/personBObj.xml"; OutputStream out = null; InputStream input = null; File file = new File(fileName); XStream xstream = initXStream(); PersonBObj personBObj = personBObjInit(); try { // 对象生成XML文件 out = new FileOutputStream(fileName); xstream.toXML(personBObj, out); Assert.assertTrue(file.exists()); // XML文件转对象 input = new FileInputStream(fileName); PersonBObj fromFileBObj = (PersonBObj) xstream.fromXML(input); Assert.assertEquals("1", fromFileBObj.getContId()); } finally { out.close(); input.close(); } if (file.exists()) { file.delete(); } }
/** * 对象转String, String转回对象 */ @Test public void testFromString() { XStream xStream = initXStream(); // 对象转XML PersonBObj personBObj = personBObjInit(); String xml = xStream.toXML(personBObj); Assert.assertNotNull(xml); // XML转对象 PersonBObj fromXMLObj = (PersonBObj) xStream.fromXML(xml); Assert.assertEquals("1", fromXMLObj.getContId()); }
/** * 初始化 XStream 对象 */ private XStream initXStream() { XStream xstream = new XStream(); // 以下为对象属性起别名 xstream.alias("OrgNameBObj", OrgNameBObj.class); xstream.alias("ContactBObj", ContactBObj.class); xstream.alias("IdentifierBObj", IdentifierBObj.class); xstream.alias("ConteQuivBObj", ConteQuivBObj.class); xstream.alias("AddressBObj", AddressBObj.class); xstream.alias("ContactMethodBObj", ContactMethodBObj.class); xstream.alias("RelativePersonBObj", RelativePersonBObj.class); xstream.alias("OrgBObj", OrgBObj.class); xstream.alias("PersonBObj", PersonBObj.class); xstream.alias("PersonNameBObj", PersonNameBObj.class); xstream.aliasField("OrgNameBObjs", OrgBObj.class, "orgNameBObjs"); xstream.aliasField("IdentifierBObjs", OrgBObj.class, "identifierBObjs"); xstream.aliasField("ContEquivBObjs", OrgBObj.class, "contEquivBObjs"); xstream.aliasField("AddressBObjs", OrgBObj.class, "addressBObjs"); xstream.aliasField("ContactMethodBObjs", OrgBObj.class, "contactMethodBObjs"); xstream.aliasField("RelativePersonBObjs", OrgBObj.class, "relativePersonBObjs"); xstream.aliasField("PersonNameBObjs", PersonBObj.class, "personNameBObjs"); xstream.aliasField("IdentifierBObjs", PersonBObj.class, "identifierBObjs"); xstream.aliasField("ContEquivBObjs", PersonBObj.class, "contEquivBObjs"); xstream.aliasField("AddressBObjs", PersonBObj.class, "addressBObjs"); xstream.aliasField("ContactMethodBObjs", PersonBObj.class, "contactMethodBObjs"); return xstream; }