Xstream - 快速指南


XStream - 概述

XStream 是一个简单的基于 Java 的库,用于将 Java 对象序列化为 XML,反之亦然。

特征

  • 易于使用- XStream API 提供了一个高级外观来简化常见用例。

  • 无需创建映射- XStream API 为大多数要序列化的对象提供默认映射。

  • 性能- XStream 速度快且内存占用低,适用于大型对象图或系统。

  • 干净的 XML - XStream 生成干净、紧凑、易于阅读的 XML 输出。

  • 不需要对象修改- XStream 序列化内部字段(如私有字段和最终字段),并支持非公共类和内部类。默认构造函数不是强制要求。

  • 完整的对象图支持- XStream 允许维护对象模型中遇到的重复引用,并且还支持循环引用。

  • 可定制的转换策略- 可以注册自定义策略,以便允许将特定类型的定制表示为 XML。

  • 安全框架- XStream 提供对未编组类型的公平控制,以防止操纵输入的安全问题。

  • 错误消息- 当由于 XML 格式错误而发生异常时,它会提供详细的诊断来解决问题。

  • 替代输出格式- XStream 支持其他输出格式,例如 JSON 和变形。

常见用途

  • 传输- XML 是对象的文本表示形式,可用于通过线路传输对象,与所使用的序列化/反序列化技术无关。

  • 持久性- 对象可以作为 XML 持久保存在数据库中,并且可以根据需要进行编组/解组。

  • 配置- XML 是不言自明的,并且大量用于定义配置。将对象转换为 XML 表示形式后,还可以将其用于配置目的。

  • 单元测试- XStream API 与 JUnit 兼容,可用于增强应用程序模块的单元测试。

XStream - 环境设置

在本章中,我们将讨论建立合适的 Java 环境的各个方面。

本地环境设置

如果您想设置 Java 编程语言的环境,本节将介绍如何在您的计算机上下载并设置 Java。请按照以下步骤设置您的 Java 环境。

Java SE 可以从链接免费下载 -

下载Java .

按照说明下载 Java 并运行 .exe在您的计算机上安装 Java。在计算机上安装 Java 后,您需要设置环境变量以指向正确的安装目录 -

设置 Windows 2000/XP 的路径

假设您已将 Java 安装在c:\Program Files\java\jdk目录中 -

  • 右键单击“我的电脑”并选择“属性”。

  • 单击“高级”选项卡下的“环境变量”按钮。

  • 更改“Path”变量,使其也包含 Java 可执行文件的路径。例如,如果路径当前设置为“C:\WINDOWS\SYSTEM32”,则将路径更改为“C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin”。

设置Windows 95/98/ME的路径

假设您已将 Java 安装在c:\Program Files\java\jdk目录中 -

  • 编辑“C:\autoexec.bat”文件并在末尾添加以下行 -

    '设置路径 = %PATH%;C:\Program Files\java\jdk\bin'

设置 Linux、UNIX、Solaris、FreeBSD 的路径

应将环境变量 PATH 设置为指向 Java 二进制文件的安装位置。如果您在执行此操作时遇到问题,请参阅您的 shell 文档。

例如,如果您使用bash作为 shell,那么您可以在 '.bashrc:export PATH=/path/to/java:$PATH' 的末尾添加以下行

流行的 Java 编辑器

要编写 Java 程序,您将需要一个文本编辑器。市场上还有更复杂的 IDE。但现在,您可以考虑以下其中一项 -

  • 记事本- 在 Windows 上,您可以使用任何简单的文本编辑器,例如记事本(本教程推荐)或 TextPad。

  • Netbeans - 它是一个免费的 Java IDE,可以从https://www.netbeans.org/index.html下载。

  • Eclipse - 它也是由 eclipse 开源社区开发的 Java IDE,可以从https://www.eclipse.org/下载。

下载 XStream 存档

从XStream 下载页面下载最新版本的 XStream jar 文件。在编写本教程时,我们已经下载了xstream-1.4.18.jar并将其复制到 C:\>XStream 文件夹中。

操作系统 档案名称
Windows xstream-1.4.18.jar
Linux xstream-1.4.18.jar
苹果 xstream-1.4.18.jar

设置XStream环境

将XStream_HOME环境变量设置为指向计算机上存储 xstream jar 的基本目录位置。下表显示了如何在 Windows、Linux 和 Mac 上设置 XStream 环境,假设我们已将 xstream-1.4.18.jar 提取到 XStream 文件夹中。

先生。 操作系统和描述
1

Windows

将环境变量 XStream_HOME 设置为 C:\XStream

2

Linux

导出 XStream_HOME=/usr/local/XStream

3

苹果

导出 XStream_HOME=/库/XStream

设置 CLASSPATH 变量

设置CLASSPATH环境变量以指向 XStream jar 位置。下表显示了如何在 Windows、Linux 和 Mac 系统上设置 CLASSPATH 变量,假设我们已将 xstream-1.4.18.jar 存储在 XStream 文件夹中。

先生。 操作系统和描述
1

Windows

设置环境变量CLASSPATH为%CLASSPATH%;%XStream_HOME%\xstream-1.4.18.jar;

2

Linux

导出 CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar;

3

苹果

导出 CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar;

XStream - 第一个应用程序

在详细介绍 XStream 库之前,让我们先看一个实际应用程序。在此示例中,我们创建了 Student 和 Address 类。我们将创建一个学生对象,然后将其序列化为 XML 字符串。然后反序列化相同的 XML 字符串以获取学生对象。

在 C:\>XStream_WORKSPACE 中创建一个名为 XStreamTester 的 java 类文件。

文件:XStreamTester.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XStreamTester {

   public static void main(String args[]) {
      XStreamTester tester = new XStreamTester();
      XStream xstream = new XStream(new StaxDriver());
      
      Student student = tester.getStudentDetails();
      
      //Object to XML Conversion
      String xml = xstream.toXML(student);
      System.out.println(formatXml(xml));
      
      //XML to Object Conversion
      Student student1 = (Student)xstream.fromXML(xml);
      System.out.println(student1);
   }
   
   private Student getStudentDetails() {
   
      Student student = new Student();
      student.setFirstName("Mahesh");
      student.setLastName("Parashar");
      student.setRollNo(1);
      student.setClassName("1st");

      Address address = new Address();
      address.setArea("H.No. 16/3, Preet Vihar.");
      address.setCity("Delhi");
      address.setState("Delhi");
      address.setCountry("India");
      address.setPincode(110012);

      student.setAddress(address);
      return student;
   }
   
   public static String formatXml(String xml) {
   
      try {
         Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
         
         serializer.setOutputProperty(OutputKeys.INDENT, "yes");
         serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
         
         Source xmlSource = new SAXSource(new InputSource(
            new ByteArrayInputStream(xml.getBytes())));
         StreamResult res =  new StreamResult(new ByteArrayOutputStream());            
         
         serializer.transform(xmlSource, res);
         
         return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
         
      } catch(Exception e) {
         return xml;
      }
   }
}

class Student {
   private int rollNo;
   private String firstName;
   private String lastName;
   private String className;
   private Address address;

   public String getFirstName() {
      return firstName;
   }
   
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   
   public String getLastName() {
      return lastName;
   }
   
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   
   public int getRollNo() {
      return rollNo;
   }
   
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   
   public String getClassName() {
      return className;
   }
   
   public void setClassName(String className) {
      this.className = className;
   }
   
   public Address getAddress() {
      return address;
   }
   
   public void setAddress(Address address) {
      this.address = address;
   }
   
   public String toString() {
      StringBuilder stringBuilder = new StringBuilder();
      
      stringBuilder.append("Student [ ");
      stringBuilder.append("\nfirstName: ");
      stringBuilder.append(firstName);
      stringBuilder.append("\nlastName: ");
      stringBuilder.append(lastName);
      stringBuilder.append("\nrollNo: ");
      stringBuilder.append(rollNo);
      stringBuilder.append("\nclassName: ");
      stringBuilder.append(className);
      stringBuilder.append("\naddress: ");
      stringBuilder.append(address);
      stringBuilder.append(" ]");
      
      return stringBuilder.toString();
   }
}

class Address {
   private String area;
   private String city;
   private String state;
   private String country;
   private int pincode;

   public String getArea() {
      return area;
   }

   public void setArea(String area) {
      this.area = area;
   }

   public String getCity() {
      return city;
   }

   public void setCity(String city) {
      this.city = city;
   }

   public String getState() {
      return state;
   }

   public void setState(String state) {
      this.state = state;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }

   public int getPincode() {
      return pincode;
   }

   public void setPincode(int pincode) {
      this.pincode = pincode;
   }

   public String toString() {

      StringBuilder stringBuilder = new StringBuilder();

      stringBuilder.append("\nAddress [ ");
      stringBuilder.append("\narea: ");
      stringBuilder.append(area);
      stringBuilder.append("\ncity: ");
      stringBuilder.append(city);
      stringBuilder.append("\nstate: ");
      stringBuilder.append(state);
      stringBuilder.append("\ncountry: ");
      stringBuilder.append(country);
      stringBuilder.append("\npincode: ");	
      stringBuilder.append(pincode);
      stringBuilder.append(" ]");

      return stringBuilder.toString();
   }
}

验证结果

使用javac编译器编译类,如下所示 -

C:\XStream_WORKSPACE>javac XStreamTester.java

现在运行 XStreamTester 查看结果 -

C:\XStream_WORKSPACE>java XStreamTester

验证输出如下

<?xml version = "1.0" encoding = "UTF-8"?>
<Student>
   <firstName>Mahesh</firstName>
   <lastName>Parashar</lastName>
   <rollNo>1</rollNo>
   <className>1st</className>
   <address>
      <area>H.No. 16/3, Preet Vihar.</area>
      <city>Delhi</city>
      <state>Delhi</state>
      <country>India</country>
      <pincode>110012</pincode>
   </address>
</Student>

Student [ 
   firstName: Mahesh
   lastName: Parashar
   rollNo: 1
   className: 1st
   address: 
   Address [ 
      area: H.No. 16/3, Preet Vihar.
      city: Delhi
      state: Delhi
      country: India
      pincode: 110012
   ] 
]

需要记住的步骤

以下是此处需要考虑的重要步骤。

步骤 1 - 创建 XStream 对象

通过向 XStream 对象传递 StaxDriver 来创建它。StaxDriver 使用 Stax pull 解析器(可从 java 6 获得),是一个快速的 xml 解析器。

XStream xstream = new XStream(new StaxDriver());

步骤 2 - 将对象序列化为 XML

使用 toXML() 方法获取对象的 XML 字符串表示形式。

//Object to XML Conversion
String xml = xstream.toXML(student);

步骤 3 - 反序列化 XML 以获取对象

使用 fromXML() 方法从 XML 中获取对象。

//XML to Object Conversion		
Student student1 = (Student)xstream.fromXML(xml);

XStream - 别名

别名是一种通过 XStream 自定义生成的 XML 或使用特定格式的 XML 的技术。假设以下 XML 格式用于序列化/反序列化 Student 对象。

<student name = "Suresh">
   <note>
      <title>first</title>
      <description>My first assignment.</description>
   </note>
   
   <note>
      <title>second</title>
      <description>My second assignment.</description>
   </note>
</student>

基于上面的XML格式,让我们创建模型类。

class Student {
   private String studentName;
   private List<Note> notes = new ArrayList<Note>();
   
   public Student(String name) {
      this.studentName = name;
   }
   
   public void addNote(Note note) {
      notes.add(note);
   }
   
   public String getName() {
      return studentName;
   }
   
   public List<Note> getNotes() {
      return notes;
   }
}

class Note {
   private String title;
   private String description;

   public Note(String title, String description) {
      this.title = title;
      this.description = description;
   }

   public String getTitle() {
      return title;
   }

   public String getDescription() {
      return description;
   }     
}

让我们使用 XStream 测试上述对象序列化。

在 C:\>XStream_WORKSPACE\com\tutorialspoint\xstream 中创建名为 XStreamTester 的 java 类文件。

文件:XStreamTester.java

package com.tutorialspoint.xstream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XStreamTester {
   public static void main(String args[]) {
   
      XStreamTester tester = new XStreamTester();
      XStream xstream = new XStream(new StaxDriver());
      Student student = tester.getStudentDetails();
      
      //Object to XML Conversion
      String xml = xstream.toXML(student);
      System.out.println(formatXml(xml));		
   }	

   private Student getStudentDetails() {
   
      Student student = new Student("Mahesh");
      
      student.addNote(new Note("first","My first assignment."));
      student.addNote(new Note("second","My Second assignment."));
      
      return student;
   }

   public static String formatXml(String xml) {
   
      try {
         Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
         
         serializer.setOutputProperty(OutputKeys.INDENT, "yes");
         serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
         
         Source xmlSource = new SAXSource(new InputSource(
            new ByteArrayInputStream(xml.getBytes())));
         StreamResult res =  new StreamResult(new ByteArrayOutputStream());            
         
         serializer.transform(xmlSource, res);
         
         return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
         
      } catch(Exception e) {
         return xml;
      }
   }
}

class Student {
   private String studentName;
   private List<Note> notes = new ArrayList<Note>();
   
   public Student(String name) {
      this.studentName = name;
   }
   
   public void addNote(Note note) {
      notes.add(note);
   }
   
   public String getName() {
      return studentName;
   }
   
   public List<Note> getNotes() {
      return notes;
   }
}

class Note {
   private String title;
   private String description;
   
   public Note(String title, String description) {
      this.title = title;
      this.description = description;
   }
   
   public String getTitle() {
      return title;
   }
   
   public String getDescription() {
      return description;
   }     
}

验证结果

使用javac编译器编译类,如下所示 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java

现在运行 XStreamTester 查看结果 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester

验证输出如下 -

<?xml version = "1.0" encoding = "UTF-8"?>
<com.tutorialspoint.xstream.Student>
   <studentName>Mahesh</studentName>
   <notes>
      <com.tutorialspoint.xstream.Note>
         <title>first</title>
         <description>My first assignment.</description>
      </com.tutorialspoint.xstream.Note>
      
      <com.tutorialspoint.xstream.Note>
         <title>second</title>
         <description>My Second assignment.</description>
     </com.tutorialspoint.xstream.Note>
   </notes>
</com.tutorialspoint.xstream.Student>

在上面的结果中,Student 对象名称是完全限定的。要将其替换为学生标签,请按照下一部分进行操作。

XStream - 注释

XStream 支持注释,类似于自动配置而不是编码。在上一章中,我们在代码中看到了以下配置。

xstream.alias("student", Student.class);
xstream.alias("note", Note.class);

xstream.useAttributeFor(Student.class, "studentName");
xstream.aliasField("name", Student.class, "studentName");
xstream.addImplicitCollection(Student.class, "notes");

以下代码片段说明了如何使用注释以更简单的方式完成相同的工作。

@XStreamAlias("student")   //define class level alias
class Student {

   @XStreamAlias("name")   //define field level alias
   @XStreamAsAttribute     //define field as attribute
   private String studentName;
   
   @XStreamImplicit        //define list as an implicit collection
   private List<Note> notes = new ArrayList<Note>();
   
   @XStreamOmitField       //omit a field to not to be a part of XML
   private int type;
}

让我们使用 XStream 测试上面的注释。

在 C:\>XStream_WORKSPACE\com\tutorialspoint\xstream 中创建名为 XStreamTester 的 java 类文件。

文件:XStreamTester.java

package com.tutorialspoint.xstream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XStreamTester {

   public static void main(String args[]) {

      XStreamTester tester = new XStreamTester();
      XStream xstream = new XStream(new StaxDriver());
      Student student = tester.getStudentDetails();
      
      xstream.processAnnotations(Student.class);		

      //Object to XML Conversion
      String xml = xstream.toXML(student);
      System.out.println(formatXml(xml));		
   }
   
   private Student getStudentDetails() {
   
      Student student = new Student("Mahesh");
      
      student.addNote(new Note("first","My first assignment."));
      student.addNote(new Note("second","My Second assignment."));
      student.setType(1);
      
      return student;
   }

   public static String formatXml(String xml) {
   
      try {
         Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
         
         serializer.setOutputProperty(OutputKeys.INDENT, "yes");
         serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
         
         Source xmlSource = new SAXSource(new InputSource(
            new ByteArrayInputStream(xml.getBytes())));
         StreamResult res = new StreamResult(new ByteArrayOutputStream());            
         
         serializer.transform(xmlSource, res);
         
         return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
         
      } catch(Exception e) {
         return xml;
      }
   }
}

@XStreamAlias("student")
class Student {

   @XStreamAlias("name")
   @XStreamAsAttribute   
   private String studentName;

   @XStreamImplicit
   private List<Note> notes = new ArrayList<Note>();

   public Student(String name) {
      this.studentName = name;
   }

   public void addNote(Note note) {
      notes.add(note);
   }

   public String getName() {
      return studentName;
   }

   public List<Note> getNotes() {
      return notes;
   }
   
   @XStreamOmitField		
   private int type;

   public int getType() {
      return type;
   }

   public void setType(int type) {
      this.type = type;
   }
}

@XStreamAlias("note")
class Note {
   private String title;
   private String description;

   public Note(String title, String description) {
      this.title = title;
      this.description = description;
   }

   public String getTitle() {
      return title;
   }

   public String getDescription() {
      return description;
   }     
}

验证结果

使用javac编译器编译类,如下所示 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java

现在运行 XStreamTester 查看结果 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester

验证输出如下 -

<?xml version = "1.0" encoding = "UTF-8"?>
<student name = "Mahesh">
   <note>
      <title>first</title>
      <description>My first assignment.</description>
   </note>

   <note>
      <title>second</title>
      <description>My Second assignment.</description>
   </note>
</student>

为了指示XStream框架处理注解,需要在序列化xml之前添加以下命令。

xstream.processAnnotations(Student.class);		

或者

xstream.autodetectAnnotations(true);

XStream - 转换器

XStream 转换器是 XStream 库的关键组件,负责将对象转换为 XML,反之亦然。XStream 为常见类型(如基元、字符串、文件、集合、数组和日期)提供了大量转换器。

使用转换器

让我们使用 SingleValueConvertor ,其目的是将对象转换为单个字符串。我们将使用 SingleValueConvertor 将对象写入属性字符串。

创建转换器

class NameConverter implements SingleValueConverter {

   public Object fromString(String name) {
      String[] nameparts = name.split(",");
      return new Name(nameparts[0], nameparts[1]);
   }
   
   public String toString(Object name) {
      return ((Name)name).getFirstName() + "," + ((Name)name).getLastName();
   }
   
   public boolean canConvert(Class type) {
      return type.equals(Name.class);
   }	
}

注册转换器

xstream.registerConverter(new NameConverter());

没有转换器的示例

让我们首先在 XStream 中测试没有转换器的代码。

在 C:\>XStream_WORKSPACE\com\tutorialspoint\xstream 中创建名为 XStreamTester 的 java 类文件。

文件:XStreamTester.java

package com.tutorialspoint.xstream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XStreamTester {
   public static void main(String args[]) {
   
      XStreamTester tester = new XStreamTester();
      XStream xstream = new XStream(new StaxDriver());
      Student student = tester.getStudentDetails();
      xstream.autodetectAnnotations(true);
      
      //Object to XML Conversion
      String xml = xstream.toXML(student);
      System.out.println(formatXml(xml));
   }
   
   private Student getStudentDetails() {
      Student student = new Student("Mahesh","Parashar");
      return student;
   }
   
   public static String formatXml(String xml) {
   
      try {
      
         Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
         
         serializer.setOutputProperty(OutputKeys.INDENT, "yes");
         serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
         
         Source xmlSource = new SAXSource(new InputSource(
            new ByteArrayInputStream(xml.getBytes())));
         StreamResult res =  new StreamResult(new ByteArrayOutputStream());
         
         serializer.transform(xmlSource, res);
         
         return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
         
      } catch(Exception e) {
         return xml;
      }
   }
}

@XStreamAlias("student")
class Student {

   @XStreamAlias("name")
   @XStreamAsAttribute
   private Name studentName;

   public Student(String firstName, String lastName) {
      this.studentName = new Name(firstName, lastName);
   }

   public Name getName() {
      return studentName;
   }	
}

class Name {
   private String firstName;
   private String lastName;

   public Name(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   public String getFirstName() {
      return firstName;
   }

   public String getLastName() {
      return lastName;
   }     
}

验证结果

使用javac编译器编译类,如下所示 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java

现在运行 XStreamTester 查看结果 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester

验证输出如下 -

<?xml version = "1.0" encoding = "UTF-8"?>
<student>
   <name>
      <firstName>Mahesh</firstName>
      <lastName>Parashar</lastName>
   </name>
</student>

带转换器的示例

现在让我们使用 XStream 中的转换器测试代码。

在 C:\>XStream_WORKSPACE\com\tutorialspoint\xstream 中创建名为 XStreamTester 的 java 类文件。

文件:XStreamTester.java

package com.tutorialspoint.xstream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XStreamTester {

   public static void main(String args[]) {
   
      XStreamTester tester = new XStreamTester();
      XStream xstream = new XStream(new StaxDriver());
      Student student = tester.getStudentDetails();		
      
      xstream.autodetectAnnotations(true);
      xstream.registerConverter(new NameConverter());
      
      //Object to XML Conversion
      String xml = xstream.toXML(student);
      System.out.println(formatXml(xml));		
   }	

   private Student getStudentDetails() {
      Student student = new Student("Mahesh","Parashar");		
      return student;
   }

   public static String formatXml(String xml) {

      try {
      
         Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
         
         serializer.setOutputProperty(OutputKeys.INDENT, "yes");         
         serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
         
         Source xmlSource = new SAXSource(new InputSource(
            new ByteArrayInputStream(xml.getBytes())));
         StreamResult res = new StreamResult(new ByteArrayOutputStream());            
         
         serializer.transform(xmlSource, res);
         
         return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
         
      } catch(Exception e) {   
         return xml;
      }
   }
}

@XStreamAlias("student")
class Student {

   @XStreamAlias("name")
   @XStreamAsAttribute	
   private Name studentName;

   public Student(String firstName, String lastName) {
      this.studentName = new Name(firstName, lastName);
   }

   public Name getName() {
      return studentName;
   }	
}

class Name {
   private String firstName;
   private String lastName;

   public Name(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   public String getFirstName() {
      return firstName;
   }

   public String getLastName() {
      return lastName;
   }     
}

class NameConverter implements SingleValueConverter  {

   public Object fromString(String name) {
      String[] nameparts = name.split(",");
      return new Name(nameparts[0], nameparts[1]);
   }

   public String toString(Object name) {
      return ((Name)name).getFirstName() + "," + ((Name)name).getLastName();
   }

   public boolean canConvert(Class type) {
      return type.equals(Name.class);
   }
}

验证结果

使用javac编译器编译类,如下所示 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java

现在运行 XStreamTester 查看结果 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester

验证输出如下 -

<?xml version = "1.0" encoding = "UTF-8"?>
<student name = "Mahesh,Parashar"/>

定制转换器

XStream - 对象流

XStream 提供了 java.io.ObjectInputStream 和 java.io.ObjectOutputStream 的替代实现,以便可以从 XML 序列化或反序列化对象流。当要处理大量对象时,这特别有用,一次将一个对象保留在内存中。

语法:createObjectOutputStream()

ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream(
   new FileOutputStream("test.txt"));

语法:createObjectInputStream()

ObjectInputStream objectInputStream = xstream.createObjectInputStream(
   new FileInputStream("test.txt"));

现在让我们使用 XStream 中的对象流测试代码。

在 C:\>XStream_WORKSPACE\com\tutorialspoint\xstream 中创建名为 XStreamTester 的 java 类文件。

文件:XStreamTester.java

package com.tutorialspoint.xstream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XStreamTester {
   public static void main(String args[]) {
   
      XStreamTester tester = new XStreamTester();
      XStream xstream = new XStream(new StaxDriver());
      
      xstream.autodetectAnnotations(true);
      
      Student student1 = new Student("Mahesh","Parashar");
      Student student2 = new Student("Suresh","Kalra");
      Student student3 = new Student("Ramesh","Kumar");
      Student student4 = new Student("Naresh","Sharma");
      
      try {
      
         ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream(
            new FileOutputStream("test.txt"));
         
         objectOutputStream.writeObject(student1);
         objectOutputStream.writeObject(student2);
         objectOutputStream.writeObject(student3);
         objectOutputStream.writeObject(student4);
         objectOutputStream.writeObject("Hello World");
         
         objectOutputStream.close();
         
         ObjectInputStream objectInputStream = xstream.createObjectInputStream(
            new FileInputStream("test.txt"));
         
         Student student5 = (Student)objectInputStream.readObject();
         Student student6 = (Student)objectInputStream.readObject();
         Student student7 = (Student)objectInputStream.readObject();
         Student student8 = (Student)objectInputStream.readObject();
         
         String text = (String)objectInputStream.readObject();
         
         System.out.println(student5);
         System.out.println(student6);
         System.out.println(student7);
         System.out.println(student8);
         System.out.println(text);
      
      } catch (IOException e) {
         e.printStackTrace();
         
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      }
   }
}

@XStreamAlias("student")
class Student {

   private String firstName;
   private String lastName;
   
   public Student(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   public String getFirstName() {
      return firstName;
   }

   public String getLastName() {
      return lastName;
   }   

   public String toString() {
      return "Student [ firstName: "+firstName+", lastName: "+ lastName+ " ]";
   }	
}

验证结果

使用javac编译器编译类,如下所示 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java

现在运行 XStreamTester 查看结果 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester

验证输出如下 -

Student [ firstName: Mahesh, lastName: Parashar ]
Student [ firstName: Suresh, lastName: Kalra ]
Student [ firstName: Ramesh, lastName: Kumar ]
Student [ firstName: Naresh, lastName: Sharma ]
Hello World

查看 C:\>XStream_WORKSPACE\com\tutorialspoint\xstream 文件夹中的 test.txt 的内容。

<?xml version = "1.0" ?>
<object-stream>
   <student>
      <firstName>Mahesh</firstName>
      <lastName>Parashar</lastName>
   </student>
   
   <student>
      <firstName>Suresh</firstName>
      <lastName>Kalra</lastName>
   </student>
   
   <student>
      <firstName>Ramesh</firstName>
      <lastName>Kumar</lastName>
   </student>
   
   <student>
      <firstName>Naresh</firstName>
      <lastName>Sharma</lastName>
   </student>
   <string>Hello World</string>
</object-stream>

XStream - 使用 XStream 编写 JSON

XStream 通过使用适当的驱动程序初始化 XStream 对象来支持 JSON。XStream 目前支持 JettisonMappedXmlDriver 和 JsonHierarchicalStreamDriver。

现在让我们用 XStream 中的 json 处理来测试代码。

在 C:\>XStream_WORKSPACE\com\tutorialspoint\xstream 中创建名为 XStreamTester 的 java 类文件。

文件:XStreamTester.java

package com.tutorialspoint.xstream;

import java.io.Writer;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

public class XStreamTester {

   public static void main(String args[]) {

      XStreamTester tester = new XStreamTester();
      XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
      
         public HierarchicalStreamWriter createWriter(Writer writer) {
            return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
         }
      });

      Student student = new Student("Mahesh","Parashar");

      xstream.setMode(XStream.NO_REFERENCES);
      xstream.alias("student", Student.class);
      
      System.out.println(xstream.toXML(student));
   }
}

@XStreamAlias("student")
class Student {

   private String firstName;
   private String lastName;

   public Student(String firstName, String lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   public String getFirstName() {
      return firstName;
   }

   public String getLastName() {
      return lastName;
   }   
	
   public String toString() {
      return "Student [ firstName: "+firstName+", lastName: "+ lastName+ " ]";
   }	
}

验证结果

使用javac编译器编译类,如下所示 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>javac XStreamTester.java

现在运行 XStreamTester 查看结果 -

C:\XStream_WORKSPACE\com\tutorialspoint\xstream>java XStreamTester

验证输出如下 -

{
   "firstName": "Mahesh",
   "lastName": "Parashar"
}