SoFunction
Updated on 2025-05-04

Brief analysis of how to use xstream to realize javaBean and xml transfer

XStream is a library for converting Java objects to XML. It is very simple to use and is suitable for rapid development and prototyping. The following will introduce in detail how to use XStream to implement the interchange between JavaBean and XML, and provide specific code examples.

1. Introduce dependencies

First, make sure you introduce XStream dependencies into your project. If you are using the Maven build tool, you can add the following dependencies to the project's file:

<dependency>
    <groupId></groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.19</version> <!-- Check if there is an updated version -->
</dependency>

2. Definition of JavaBean

Suppose there is a simple Person class that contains name, age, and address information:

public class Person {
    private String name;
    private int age;
    private Address address;
 
    // Getters and Setters
 
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address=" + address +
                '}';
    }
 
    public static class Address {
        private String street;
        private String city;
        private String state;
 
        // Getters and Setters
 
        @Override
        public String toString() {
            return "Address{" +
                    "street='" + street + '\'' +
                    ", city='" + city + '\'' +
                    ", state='" + state + '\'' +
                    '}';
        }
    }
}

3. JavaBean to XML

Use XStream to convert a Person object to an XML string:

import ;
 
public class JavaBeanToXmlExample {
    public static void main(String[] args) {
        // Create Person object         address = new ();
        ("123 Main St");
        ("Anytown");
        ("Anystate");
 
        Person person = new Person();
        ("John Doe");
        (30);
        (address);
 
        // Create an XStream instance        XStream xstream = new XStream();
 
        // Convert JavaBean to XML        String xml = (person);
 
        // Output XML        (xml);
    }
}

4. XML to JavaBean

Use XStream to convert XML strings to Person objects:

import ;
 
public class XmlToJavaBeanExample {
    public static void main(String[] args) {
        // XML string        String xml = "<person>\n" +
                     "  <name>John Doe</name>\n" +
                     "  <age>30</age>\n" +
                     "  <address>\n" +
                     "    <street>123 Main St</street>\n" +
                     "    <city>Anytown</city>\n" +
                     "    <state>Anystate</state>\n" +
                     "  </address>\n" +
                     "</person>";
 
        // Create an XStream instance        XStream xstream = new XStream();
 
        // Convert XML to JavaBean        Person person = (Person) (xml);
 
        // Output JavaBean        (person);
    }
}

5. Customize the tag name

By default, XStream uses class and field names as XML tag names. If you want to customize the tag name, you can use annotation or configuration method.

Use Notes

import ;
 
@XStreamAlias("person")
public class Person {
    @XStreamAlias("full-name")
    private String name;
    @XStreamAlias("age-in-years")
    private int age;
    @XStreamAlias("address-info")
    private Address address;
 
    // Getters and Setters
 
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address=" + address +
                '}';
    }
 
    @XStreamAlias("address")
    public static class Address {
        @XStreamAlias("street-address")
        private String street;
        @XStreamAlias("city-name")
        private String city;
        @XStreamAlias("state-code")
        private String state;
 
        // Getters and Setters
 
        @Override
        public String toString() {
            return "Address{" +
                    "street='" + street + '\'' +
                    ", city='" + city + '\'' +
                    ", state='" + state + '\'' +
                    '}';
        }
    }
}

Use configuration method

import ;
 
public class CustomTagExample {
    public static void main(String[] args) {
        // Create Person object         address = new ();
        ("123 Main St");
        ("Anytown");
        ("Anystate");
 
        Person person = new Person();
        ("John Doe");
        (30);
        (address);
 
        // Create an XStream instance        XStream xstream = new XStream();
 
        // Configure custom tag names        ("person", );
        ("address", );
        ("full-name", , "name");
        ("age-in-years", , "age");
        ("address-info", , "address");
        ("street-address", , "street");
        ("city-name", , "city");
        ("state-code", , "state");
 
        // Convert JavaBean to XML        String xml = (person);
 
        // Output XML        (xml);
    }
}

Knowledge extension

Use xstream to convert objects and XML

rely

       <dependency>
            <groupId></groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.18</version>
        </dependency>

Entity Class

package ;
 
import ;
import ;
import ;
 
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    private String name;
    private int age;
}

Tools

package ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
public class XmlUtils {
 
    private static final XStream xStream = new XStream();
 
    static {
        // Allow deserialization        (new String[] { "**" });
    }
 
    /**
      * Converts Java objects to XML and writes to the specified file.
      *
      * @param <T> Java object type to convert
      * @param object Java object to convert
      * @param filePath output XML filepath
      */
    public static &lt;T&gt; void objectToXml(T object, String filePath) {
        // Define XML alias for the object        (().getSimpleName(), ());
 
        StringWriter stringWriter = new StringWriter();
        ("&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n");
 
        // Convert an object to an XML string        (object, stringWriter);
 
        // Get the file path        Path path = (filePath);
 
        // Write XML strings to a file using NIO's BufferedWriter        try (BufferedWriter writer = (path, StandardCharsets.UTF_8)) {
            (());
            ("XML content has been successfully written to the file:" + ());
        } catch (IOException e) {
            ("An error occurred while writing to an XML file: " + ());
            ();
        }
    }
 
    /**
      * Read data from an XML file and convert it into a Java object.
      *
      * @param filePath XML file path
      * @param clazz The Java class to convert to
      * @param <T> Converted object type
      * @return Converted Java object, if read or conversion fails, return null
      */
    public static &lt;T&gt; T xmlToObject(String filePath, Class&lt;T&gt; clazz) {
        Path path = (filePath);
 
        // Verify that the file exists        if (!(path)) {
            ("The specified file does not exist: " + filePath);
            return null;
        }
 
        try {
            String xml = new String((path), StandardCharsets.UTF_8);
            ((), clazz); // Define alias for the target class            return (T) (xml); // Convert directly from XML strings        } catch (IOException e) {
            ("An error occurred while reading an XML file: " + ());
            ();
        } catch (ClassCastException e) {
            ("An error occurred while converting XML data: " + ());
            ();
        }
 
        return null;
    }
}

test

package ;
 
import ;
import ;
 
public class Main {
    public static void main(String[] args) {
        // Suppose there is an object person, you need to convert it to XML        Person person = new Person("John", 30);
        String filePath = "D:/Desktop/";
 
        // Call static methods to convert objects to XML and write to files        (person, filePath);
 
        // Read and convert from XML file to object        Person readPerson = (filePath, );
        (readPerson);
    }
}

Output result:

XML content has been successfully written to the file: D:\Desktop\
Person(name=John, age=30)
D:/Desktop/File content:
<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <name>John</name>
  <age>30</age>
</Person>

Summarize

JavaBean to XML: Use XStream's toXML method to convert Java objects into XML strings.

XML to JavaBean: Use XStream's fromXML method to convert XML strings into Java objects.

Custom tag name: You can customize XML tag names using annotation or configuration methods.

The above is a detailed analysis of how to use xstream to realize the interchange of javaBean and xml. For more information about the interchange of javaBean and xml, please follow my other related articles!