Simplified API; non- ing file; high performance, low memory usage; neat XML; no need to modify objects, support for internal private fields; no need for settergetter method, final field; provide serialization interface; custom conversion type policy; detailed error diagnosis;
Features
Simplified API;
No ing file;
High performance, low memory usage;
Neat XML;
Objects do not need to be modified. internal private fields are supported;
The setter/getter method and final field are not required;
Provides serialization interfaces;
Custom conversion type policy;
Detailed error diagnosis;
Common Annotations of Xstream
@ XStreamAlias ("message") alias annotation, target: Class, field
@ XStreamImplicit implicit set
@ XStreamImplicit (itemFieldName = "part") target: set field
@ XStreamConverter (SingleValueCalendarConverter. class) injects the converter to target: Object
@ XStreamAsAttribute convert to attribute. purpose: Field
@ XStreamOmitField ignore the field. purpose: Field
Example
1. parse the XML tool class
Import com. thoughtworks. xstream. XStream; import com. thoughtworks. xstream. io. xml. domDriver; import org. slf4j. logger; import org. slf4j. loggerFactory; import java. io. *;/*** tool class for outputting xml and parsing xml */public class XmlUtil {private static final Logger logger = LoggerFactory. getLogger (XmlUtil. class);/*** convert java to xml * @ param obj object instance * @ return String xml String * @ Title: toXml * @ Description: TODO */public static String toXml (Object obj) {// XStream xstream = new XStream (); // the xpp parser is used by default. // specify the encoding parser XStream xstream = new XStream (new DomDriver ("UTF-8"); // enable annotation recognition xstream. processAnnotations (obj. getClass (); return xstream. toXML (obj );} /*** convert the incoming xml text into a Java object * @ param xmlStr * @ param cls the class corresponding to xml * @ return T the instance object of the class corresponding to xml */public static
T toBean (String xmlStr, Class
Cls) {XStream xstream = new XStream (); xstream. processAnnotations (cls); T obj = (T) xstream. fromXML (xmlStr); return obj ;} /*** write it to the xml file * @ param obj Object * @ param absPath absolute path * @ param fileName File Name */public static boolean toXMLFile (Object obj, String absPath, string fileName) {String strXml = toXml (obj); String filePath = absPath + fileName; File file = new File (filePath); if (! File. exists () {try {file. createNewFile ();} catch (IOException e) {logger. error ("file creation failed, cause is {}", e); return false ;}} OutputStream ous = null; try {ous = new FileOutputStream (file); ous. write (strXml. getBytes (); ous. flush ();} catch (Exception e1) {logger. error ("file write failed, cause is {}", e1); return false;} finally {if (ous! = Null) try {ous. close ();} catch (IOException e) {e. printStackTrace () ;}} return true;}/*** READ the packet from the xml file * @ param absPath absolute path * @ param fileName File Name * @ param cls */public static
T toBeanFromFile (String absPath, String fileName, Class
Cls) throws Exception {String filePath = absPath + fileName; InputStream ins = null; try {ins = new FileInputStream (new File (filePath);} catch (Exception e) {throw new Exception ("read {" + filePath + "} file failed! ", E);} XStream xstream = new XStream (); xstream. processAnnotations (cls); T obj = null; try {obj = (T) xstream. fromXML (ins);} catch (Exception e) {throw new Exception ("parse {" + filePath + "} file failed! ", E) ;}if (ins! = Null) ins. close (); return obj ;}}
2. Compile the Teacher class
import com.thoughtworks.xstream.annotations.XStreamAlias;import com.thoughtworks.xstream.annotations.XStreamAsAttribute;import com.thoughtworks.xstream.annotations.XStreamImplicit;import java.util.List;@XStreamAlias(value = "teacher")public class Teacher { @XStreamAsAttribute private String name; @XStreamAsAttribute private String phone; @XStreamAsAttribute private int age; @XStreamImplicit(itemFieldName = "student") private List
students; public Teacher() { } public Teacher(String name, String phone, int age, List
students) { this.name = name; this.phone = phone; this.age = age; this.students = students; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List
getStudents() { return students; } public void setStudents(List
students) { this.students = students; }}
3. Compile the Student class
import com.thoughtworks.xstream.annotations.XStreamAlias;import com.thoughtworks.xstream.annotations.XStreamAsAttribute;@XStreamAlias(value = "student")public class Student { @XStreamAsAttribute private String name; @XStreamAsAttribute private int age; @XStreamAsAttribute private String address; public Student() { } public Student(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }}
4. Test class
Import java. util. arrayList; import java. util. list; public class Test {public static void main (String [] args) {Student student1 = new Student ("Aaron", 24, "Guangzhou "); student student2 = new Student ("Abel", 23, "Beijing"); List
Students = new ArrayList <> (); students. add (student1); students. add (student2); Teacher teacher = new Teacher ("Dave", "020-123456", 46, students); String xml = XmlUtil. toXml (teacher); System. out. println (xml );}}
5. running result
The above is a detailed explanation of the Xstream sample code in the xml parsing toolkit. For more information, see other related articles in the first PHP community!