XStream string and XML, and how to read the files under the Web

Source: Internet
Author: User
Tags getmessage log4j

Sometimes in project development to transfer the XM file, to convert to string transmission, but not the use of object transfer, so to convert, used to summarize the use of XStream for string and XML objects, and in the conversion of a package of all the classes.

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, using Ant's matching pattern, such as Congfig/**/*.class, is a matching config file in the next directory or multiple directories under the class file, 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); /** * Gets an instance of all classes under a package * @param packagepath Package name * @return Class Collection/public static set<class<?>> ge
	 Tclasses (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);
	The catch (IOException e) {logger.error (E.getmessage (), E.getcause ()); 
 return classes;
 }

}

XStream convert XML As Object, it is required class of object, so the former gets class file to pave the back of the conversion

the object instance to convert, User.java


@XStreamAlias ("User") represents an alias


@XStreamAsAttribute represented 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")
	@XStreamAsAttribute
	private String Name;
	@XStreamAlias ("PassWord")
	@XStreamAsAttribute
	private 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 ("_-", "_"));

without the new Xppdriver ("_-", "_" ),

the alias takes the @xstreamalias ("Id_") and is parsed into @xstreamalias ("id__")


Xstream.processannotations (Clazz), scanning the class that will 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);
	Private XStream XStream = new XStream (New Xppdriver ("Xmlfriendlynamecoder", "_"));

	public static xstreamutils xstreamutils = null; /** * Gets a unique instance object, through a double lock * @param packagepath Package name * @return Xstreamutils 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, through a double layer 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 (P
	Ackagepath);
	 /** * Non-parametric construction * xstreamutils Construction method/Private Xstreamutils () {}/** * scans all classes labeled with Xstreamalias annotations under the package name passed in
		* @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 (XStream
					Alias.class); if (annotationfiled!= null) {xstream.processannotations (clazz);
					Break
     {}}}}/** * Converts the object under the package to a string XML form, and the class of object is already initialized.
	* @param obj object to convert * @return String */public string toXml (object obj) {return xstream.toxml (obj);
		/** * Converts an object to a string XML form * @param obj the object to convert * @return string XML/public string Toxmlsingle (object obj) {
		Xstream.processannotations (Obj.getclass ());
	return Xstream.toxml (obj); /** * Converts string XML strings to Objects * @param XML to be converted String * @param clazz to be converted to the corresponding Clazz object * @return converted object/public
		<T> T fromobjectsingle (String xml,class<t> clazz) {xstream.processannotations (clazz);
		T object = (t) xstream.fromxml (XML);
	return object; /** * Converts XML from string to object, object class has been initialized * @param XML to be converted by String * @return 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 (a);
	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.