Home Java javaTutorial XML document conversion method implemented in Javabean based on xstream package

XML document conversion method implemented in Javabean based on xstream package

May 28, 2017 am 09:19 AM

This article mainly introduces the Javabean method of converting XML documents based on the xstream package. It analyzes the specific usage skills of the xstream package for converting xml files based on specific examples. Friends in need can refer to the following

The example in this article describes how Javabean converts XML documents based on the xstream package. Share it with everyone for your reference, the details are as follows:

1. Required Jar package:

xpp3_min.jar
xstream.jar

This siteDownload address.

Add these two jars to the project

2. Add two javabeans for testing: Province and City

class Province
{
  private String name;// 省名
  private List<City> cities = new ArrayList<City>();
  public String getName()
  {
    return name;
  }
  public void setName(String name)
  {
    this.name = name;
  }
  public List<City> getCities()
  {
    return cities;
  }
  public void setCities(List<City> cities)
  {
    this.cities = cities;
  }
  public void addCity(City city)
  {
    cities.add(city);
  }
}
class City
{
  private String name;// 市名
  private String description;// 描述
  private String[] counties; // 该市的所有县
  public String getName()
  {
    return name;
  }
  public void setName(String name)
  {
    this.name = name;
  }
  public String[] getCounties()
  {
    return this.counties;
  }
  public void setCounties(String[] countries)
  {
    this.counties = countries;
  }
  public String getDescription()
  {
    return description;
  }
  public void setDescription(String description)
  {
    this.description = description;
  }
  @Override
  public String toString()
  {
    return "City [name=" + name + ", description=" + description + "]";
  }
  public City()
  {
    super();
  }
  public City(String name, String description)
  {
    super();
    this.name = name;
    this.description = description;
  }
}
Copy after login

XStream The method toXML(Object obj) is provided to return the generated xml document in the form of string. The
XStream#alias() method can change the Tag name of the generated element. If the Tag name is not set, the String form of Class will be used as the Tag name, such as: Java.lang.String.

XStream#useAttributeFor() method can convert Javabean's attribute into the attribute of xml element.

XStream#addImplicitCollection() method can convert collection elements in Javabeans, such as List, into each element directly into a sub-element without generating another element to serve as these sub-elements. parent element.

XStream#addImplicitArray() method is the same as addImplicitCollection(), except that the collection becomes an array.

The following is the test code:


package com.song.demo;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
public class BeanToXml
{
  public static void main(String[] args)
  {
    // 创建一个JavaBean
    List<Province> proList = new ArrayList<Province>();
    // 广东省
    Province gdProvince = new Province();
    gdProvince.setName("广东省");
    City gzCity = new City("广州市", "广东省省会");
    gzCity.setCounties(new String[]{"海珠区", "天河区", "白云区"});
    gdProvince.addCity(gzCity);
    gdProvince.addCity(new City("韶关", "粤北城市"));
    // 北京市
    Province bjProvince = new Province();
    bjProvince.setName("北京市");
    bjProvince.addCity(new City("东城区", "北京市东城区"));
    bjProvince.addCity(new City("西城区", "北京市西城区"));
    proList.add(gdProvince);
    proList.add(bjProvince);
    // 使用默认的方式生成xml
    // System.out.println(toXML1(proList));
    // 处理JavaBean中的集合属性,直接生成子节点
    System.out.println(toXml2(proList));
  }
  private static String toXml2(Object obj)
  {
    XStream stream = new XStream();
    // 更改List类型的元素的显示名称
    stream.alias("中国", List.class);
    stream.alias("省份", Province.class);
    stream.alias("城市", City.class);
    stream.alias("区-县", String.class);
    // 把Province类中的name属性生成为元素的属性
    stream.useAttributeFor(Province.class, "name");
    // 把JavaBean中的集合元素直接变成子节点,面不另外再生成一个节点,该节点包含所有的子节点:
    // 如:
    /*
     * <cities>
     * <city />
     * <city />
     * </cities>
     *
     * 转换成:
     * <city />
     * <city />
     */
    // 集合类型:cities为List类型
    stream.addImplicitCollection(Province.class, "cities");
    // 数组类型:counties为String[] 类型
    stream.addImplicitArray(City.class, "counties");
    return stream.toXML(obj);
  }
}
Copy after login

Test result:


##

<中国>
 <省份 name="广东省">
  <城市>
   <name>广州市</name>
   <description>广东省省会</description>
   <区-县>海珠区</区-县>
   <区-县>天河区</区-县>
   <区-县>白云区</区-县>
  </城市>
  <城市>
   <name>韶关</name>
   <description>粤北城市</description>
  </城市>
 </省份>
 <省份 name="北京市">
  <城市>
   <name>东城区</name>
   <description>北京市东城区</description>
  </城市>
  <城市>
   <name>西城区</name>
   <description>北京市西城区</description>
  </城市>
 </省份>
</中国>
Copy after login

The above is the detailed content of XML document conversion method implemented in Javabean based on xstream package. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Filtering and sorting XML data using Python Filtering and sorting XML data using Python Aug 07, 2023 pm 04:17 PM

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Handling errors and exceptions in XML using Python Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python implements conversion between XML and JSON Python implements conversion between XML and JSON Aug 07, 2023 pm 07:10 PM

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Python parsing special characters and escape sequences in XML Python parsing special characters and escape sequences in XML Aug 08, 2023 pm 12:46 PM

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

Data synchronization between XML and database using Python Data synchronization between XML and database using Python Aug 07, 2023 pm 01:10 PM

Using Python to implement data synchronization between XML and database Introduction: In the actual development process, it is often necessary to synchronize XML data with database data. XML is a commonly used data exchange format, and database is an important tool for storing data. This article will introduce how to use Python to achieve data synchronization between XML and database, and give code examples. 1. Basic concepts of XML and database XML (ExtensibleMarkupLanguage) is an extensible

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

See all articles