Xml parsing toolkit Xstream Sample code

Source: Internet
Author: User
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

  1. Simplified API;

  2. No ing file;

  3. High performance, low memory usage;

  4. Neat XML;

  5. Objects do not need to be modified. internal private fields are supported;

  6. The setter/getter method and final field are not required;

  7. Provides serialization interfaces;

  8. Custom conversion type policy;

  9. 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!

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.