XStream is a tool for translating Java objects and XML into one another, very good and powerful. Provides support for the direct conversion of all types, arrays, collections, and so on.
The core class in XStream is the XStream class, which is generally sufficient to be familiar with this class.
Since Xstream.jar relies on xmlpull.jar, you need to import these two jars together.
: Https://pan.baidu.com/s/1eSpZs3o#path=%252F%25E5%25B7%25A5%25E5%2585%25B7jar
The XStream object is quite a translator between Java objects and XML, and the conversion process is bidirectional. The way to create Xsteam objects is simple, just new XStream () is required. Java to XML, withToXML ()Method. XML to Java, withFromXml ()Method. The alias configuration consists of three cases: 1, the class name,alias (String name, Class type)。 2, class member Alias, withAliasfield (String alias, Class Definedin, string fieldName)3, class members as attribute aliases, withAliasattribute (Class Definedin, String attributename, string alias), the name alone is meaningless, anduseattributefor (Class Definedin, String fieldName)Applied to a class. The configuration of aliases is very important, but some of the details are important. Simple examples are: plain Java objects:
Package Com.test;import java.util.List; Public classPerson {Private intID; PrivateString name; PrivateList<string>Fav; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicList<string>getfav () {returnFav; } Public voidSetfav (list<string>fav) { This. fav =Fav; } }
Test class:
Import Java.util.arraylist;import Java.util.list;import com.test.person;import Com.thoughtworks.xstream.XStream; Public classXstreamtest { Public Static voidMain (string[] args) {XStream stream=NewXStream (); Person PR=NewPerson (); Pr.setid (1); Pr.setname ("Zhang San"); List<String> favs =NewArraylist<string>(); Favs.add ("Eat"); Favs.add ("Sleep"); Pr.setfav (favs); System. out. println ("before-------------alias-----------------"); System. out. println (Stream.toxml (PR)); System. out. println ("after-------------alias-----------------"); //class from AliasStream.alias (" Person", Pr.getclass ()); System. out. println (Stream.toxml (PR)); }}
Output Result:
-------------Pre-alias-----------------<com.test.Person> <id>1</id> <name> Zhang San </name> <fav> <string> Eating </string> <string > Sleeping </string> </fav></com.test.Person>-------------alias after-----------------< person> <id>1</id> <name> Zhang San </name> <fav> < string> Dinner </string> <string> Sleep </string> </fav></person>
The Java object and XML are converted to each other----xstream