商务合作:179001057@qq.com

xstream : 实现XML 与 Java Object的互转

技术2022-05-11  4


某平台价值19860元的编程课程资料免费领取【点我领取】


官方主页:http://xstream.codehaus.org/

测试代码:

import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.Dom4JDriver; import com.yycs.entity.User; public class Test { public static void main(String[] args) throws DocumentException { Configuration config = new AnnotationConfiguration().configure(); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); User user = new User(); user.setUsername("shenbin"); user.setPassword("12345678"); session.save(user); session.close(); session = sessionFactory.openSession(); user.setUsername("chenyan"); user.setPassword("87654321"); session.save(user); session.close(); session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(User.class); XStream xstream = new XStream(new Dom4JDriver()); //xstream.alias("user", User.class); xstream.processAnnotations(User.class); Document document = DocumentHelper.createDocument(DocumentHelper.createElement("yycs")); Document document1 = DocumentHelper.parseText(xstream.toXML(criteria.list())); Document document2 = DocumentHelper.parseText(xstream.toXML(criteria.list())); Element user1 = (Element)document1.selectSingleNode("//list"); Element user2 = (Element)document2.selectSingleNode("//list"); document.getRootElement().appendContent(user1); document.getRootElement().appendContent(user2); System.out.println(document.asXML()); session.close(); } }

 

注意:以上实现到Java Oject到XML的转换的代码片段,与Hibernate相关的代码就不一一提供了。

想要得到可运行的代码可直接参阅官网:http://xstream.codehaus.org/tutorial.html


最新回复(0)