adding dependencies in 1.pom.xml
<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactid>xstream </artifactId> <version>1.4. 7</version> </dependency>
2. Create the Xmlutil class and configure the XStream
2.1 Resolve Double underline: XStream occurs when an attribute such as Person_name in an object is converted to XML format <person__name> this double underline
In this way, you can replace the double underline with a single underline
// Resolve double underline Public Static New Xmlfriendlynamecoder ("-_""_");
2.2 Encoding Format:
// encoding Format Private Static " UTF-8 ";
2.3 Using the DOM parsing method
// DOM parsing driver Private Static New Domdriver (ENCODING, Namecoder);
2.4 General-purpose parser that puts the configuration into the XStream object
// Universal Parser Public Static New XStream (Fixdriver);
2.5 Date in Object note time zone processing
// Time zone Private Static " Asia/shanghai ";
2.6 Initializing XStream
Static { // timezone processing TimeZone zone = timezone.gettimezone (china_time_zone);//Get Time zone Xstream.registerconverter (new DateConverter (Zone), xstream.priority_normal); Xstream.autodetectannotations (true); Open the serialized annotation form xstream.setmode (xstream.no_references);//dereference, without this step, the XML reference format will appear reference }
3. Methods of XStream
3.1 Message Forwarding Objects
Public Static Object fromxml (String xml) { null; = XSTREAM; Xstream.processannotations (allcase. class); // The parsing of this class is turned on, otherwise it cannot be resolved Try { = xstream.fromxml (XML); Catch (Exception e) { e.printstacktrace (); } return target; }
3.2 Object Forwarding Message
Public Static String ToXML (Object obj) { = XSTREAM; String XML= xstream.toxml (obj); return xml; }
3.3 File Transfer Objects
Public StaticObject FromXml (InputStreaminch) {Object target=NULL; XStream XStream=XSTREAM; Xstream.processannotations (allcase.class); Try{target= Xstream.fromxml (inch); System. out. println ("Input Success"); } Catch(Exception e) {e.printstacktrace (); } returnTarget; }
3.4 Object Goto File stream
Public Static void out ) { = XSTREAM; Xstream.toxml (obj, out); System. out. println (" output succeeded "); }
Ps:xstream serialization and deserialization between Java objects and XML, XStream itself encapsulates the serialization method, and the Java class does not implement the Serializable interface
Xstream--java objects and XML form files to each other