XStream each other to string and XML, and how to read the file under the Web

Source: Internet
Author: User
Tags getmessage

In project development, it is sometimes necessary to transfer XM files, to convert them into string transfers, and not to use object transfer, so the conversion is done using XStream for the mutual transfer of string and XML objects, and for converting all classes under a package.

XML file parsing and creation, please refer to: http://blog.csdn.net/oyyz111/article/details/22730983

First, use spring's pathmatchingresourcepatternresolver to read a class file under a package, with Ant's matching pattern, such as Congfig/**/*.class, is a class file that matches the config file under the next directory or multiple directories, config/a/a.class or Config/a/b/b.class

The code is as follows:

Import Java.io.file;import java.io.ioexception;import Java.util.linkedhashset;import Java.util.Set;import Org.apache.log4j.logger;import Org.springframework.core.io.resource;import Org.springframework.core.io.support.pathmatchingresourcepatternresolver;import Org.springframework.core.io.support.resourcepatternresolver;public class Achievefileutils {private static Logger      Logger = Logger.getlogger (Achievefileutils.class); /** * Get instances of all classes under a package * @param packagepath Package name * @return Class Collection */public static set<class<?>> Getclas SES (String packagepath) {set<class<?>> classes = new linkedhashset<class<?>> (); String Packageclasspath = Packagepath.replace (".", "/") + "/**/*.class"; Resourcepatternresolver resolver = new pathmatchingresourcepatternresolver (); try {resource[] resources = Resolver.getresources ("classpath*:" +packageclasspath); for (int i = 0;i < Resources.length;i + +) {Resource Resource = Resources[i]; String Completefilepath = resource.GetFile (). GetPath (). Replace (File.separator, "/"); Logger.info ("Completefilepath:" +completefilepath); String className = completefilepath.substring (Completefilepath.lastindexof (Packagepath.replace (".", "/")), Completefilepath.length ()-6); try {classes.add (Class.forName (Classname.replace ("/", "."))} catch ( ClassNotFoundException e) {logger.error ("not loaded into this class"); Logger.error (E.getmessage (), E.getcause ());} Logger.info ("ClassName:" +classname);}}  catch (IOException e) {logger.error (E.getmessage (), E.getcause ());} return classes; }}

XStream transforms XML as an object, which is required for the class of the object, so the former gets the class file to pave the back for the conversion

The object instance to convert, User.java


@XStreamAlias ("User") represents an alias


@XStreamAsAttribute expressed as attributes

Import Com.thoughtworks.xstream.annotations.xstreamalias;import Com.thoughtworks.xstream.annotations.XStreamAsAttribute; @XStreamAlias ("User") public class User {@ Xstreamasattribute@xstreamalias ("id") private int ID, @XStreamAlias ("Name") @XStreamAsAttributeprivate String name;@ Xstreamalias ("PassWord") @XStreamAsAttributeprivate String password;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}

Private XStream XStream = new XStream (New Xppdriver (Newxmlfriendlynamecoder ("_-", "_"));

If there is no newXppdriver (New Xmlfriendlynamecoder ("_-", "_")),

Alias is @xstreamalias ("id_"), it is parsed into @xstreamalias ("id__")


Xstream.processannotations (clazz): Scan the class to be converted


Import Java.lang.annotation.annotation;import Java.lang.reflect.field;import Java.util.set;import Org.apache.log4j.logger;import Com.frame.model.user;import Com.thoughtworks.xstream.xstream;import Com.thoughtworks.xstream.annotations.xstreamalias;import Com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder; Import Com.thoughtworks.xstream.io.xml.xppdriver;public class Xstreamutils {private static Logger Logger = Logger.getlogger (xstreamutils.class);p rivate XStream XStream = new XStream (New Xppdriver ("Xmlfriendlynamecoder "," _ ")));p ublic static Xstreamutils xstreamutils = null;/** * Gets a unique instance object, via double lock * @param packagepath Package name * @return Xstreamut Ils object */public static xstreamutils getinstance (String packagepath) {if (xstreamutils = = null) {synchronized (xstreamutils . Class) {if (xstreamutils = = null) {xstreamutils = new xstreamutils (PackagePath);}}} return xstreamutils;} /** * Gets a unique instance object, via double lock * @return Xstreamutils object */public static Xstreamutils getinstance () {if (xstreamutils = null) {synchRonized (Xstreamutils.class) {if (xstreamutils = = null) Xstreamutils = new Xstreamutils ();}} return xstreamutils;} /** * Xstreamutils Construction method * @param packagepath */private xstreamutils (String packagepath) {this.initxstream (PackagePath);} /** * Parameterless Construction * xstreamutils Construction method */private Xstreamutils () {}/** * Scans all classes marked with Xstreamalias annotations under the package name, based on the incoming package names * @param PackagePath Package name */private void Initxstream (String packagepath) {xstream.autodetectannotations (true); set<class<?>> classes = achievefileutils.getclasses (PackagePath); for (Class clazz:classes) {Annotation annotation = clazz.getannotation (Xstreamalias.class), if (annotation! = null) {xstream.processannotations (clazz);} else {for Field field:clazz.getFields ()) {Annotation annotationfiled = field.getannotation (Xstreamalias.class);    annotationfiled = null) {xstream.processannotations (clazz); break;}}}}     /** * Converts the object under the package into a string XML form, the class of object has been initialized. * @param obj object to convert * @return string */public string toXml (Object obj) {return xstream.toxml (obj);} /** * Converts an object into a string XML form * @param obj object to be converted * @return string XML */public toxmlsingle (object obj) {Xstream.processan Notations (Obj.getclass ()); return xstream.toxml (obj);} /** * Converts an XML string of string to an object * @param XML to convert the string * @param clazz to be converted to the corresponding Clazz object * @return converted object */public <T> T from Objectsingle (String xml,class<t> clazz) {xstream.processannotations (clazz); T object = (t) xstream.fromxml (XML); return object;} /** * Converts the XML wrapped under string to an object, the class of the object has been initialized * @param the XML to be converted by the String * @return the converted object */public objects fromobject (string xml) { return Xstream.fromxml (XML);}}

Test code:

public static void Main (string[] args) {//xstreamutils x = xstreamutils.getinstance (); Xstreamutils x = xstreamutils.getinstance ("Com.frame.model"); User user = new user (); User.setid (+); User.setname ("C")    ; User.setpassword ("123"); String stringxml = x.toxmlsingle (user);     String stringxml = x.toxml (user);    System.out.println (stringxml);//User Suser  =  x.fromobjectsingle (stringxml, user.class);    User Suser  =  (user) X.fromobject (stringxml);    System.out.println (Suser.getname ());}

Results:

<user id= "name=" C "password=" 123 "/>
C

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.