当前位置: 首页 > 工具软件 > Simple XML > 使用案例 >

spring组件simple-xml的简单使用

黄宏旷
2023-12-01
<dependency>
    <groupId>org.simpleframework</groupId>
    <artifactId>simple-xml</artifactId>
    <version>2.7.1</version>
</dependency>
package xml;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.junit.Test;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * XML 数据转换 测试
 */
public class XmlConvertTest {

    public static final String CHARSET_GBK = "GBK";
    public static final String CHARSET_UTF8 = "UTF-8";

    static String filePath = "G:\\projects\\test\\myweb\\src\\main\\test\\xml\\";

    // java对象转xml
    @Test
    public void testWriteXml() throws Exception {
        String xmlContent = XmlUtil.writeXml(initStudent(), CHARSET_GBK);
        XmlUtil.writeToFile(filePath + "student.xml", CHARSET_GBK, xmlContent);
        System.out.println(xmlContent);
    }
    /*
    <?xml version="1.0" encoding="GBK" standalone="yes"?>
    <student>
       <name>tom</name>
       <age>11</age>
       <courses>
          <course>
             <cname>语文</cname>
          </course>
          <course>
             <cname>数学</cname>
          </course>
       </courses>
    </student>
    */


    // xml 转 java对象
    @Test
    public void testReadXml() throws Exception {
        String xmlContent = XmlUtil.readFromFile(filePath + "student.xml", CHARSET_GBK);
        Student student = XmlUtil.readXml(xmlContent, Student.class);
        System.out.println(student);
    }
    //Student(name=tom, age=11, courses=[Course(cname=语文), Course(cname=数学)])

    private Student initStudent(){
        Course course1 = new Course();
        course1.setCname("语文");
        Course course2 = new Course();
        course2.setCname("数学");
        List<Course> courses = new ArrayList<>();
        courses.add(course1);
        courses.add(course2);
        Student student = new Student();
        student.setName("tom");
        student.setAge("11");
        student.setCourses(courses);
        return student;
    }
}

class XmlUtil {

    public static <T> T readXml(String content, Class<T> clazz) throws Exception {
        Serializer serializer = new Persister();
        return serializer.read(clazz, content, false);
    }

    public static String writeXml(Object obj, String encoding) throws Exception {
        Format fmt = new Format("<?xml version=\"1.0\" encoding=\""+encoding+"\" standalone=\"yes\"?>");
        Serializer serializer = new Persister(fmt);
        StringWriter sw = new StringWriter();
        serializer.write(obj, sw);
        return sw.toString();
    }

    public static String readFromFile(String srcFile, String charsetName) {
        File src = new File(srcFile);
        BufferedReader bufferedReader = null;
        try {
            InputStreamReader read = new InputStreamReader(new FileInputStream(src),charsetName);
            bufferedReader = new BufferedReader(read);
            StringBuilder stringBuilder = new StringBuilder();
            String content;
            while((content = bufferedReader.readLine() )!=null){
                stringBuilder.append(content);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally{
            if (bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void writeToFile(String distFile, String charsetName, String content) {
        File src = new File(distFile);
        BufferedWriter bufferedWriter = null;
        try {
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(src),charsetName);
            bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if (bufferedWriter!=null){
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


@Getter
@Setter
@ToString
class Student {
    @Element(name = "name", required = false)
    private String name;
    @Element(name = "age", required = false)
    private String age;
    @ElementList(name = "courses", required = false, type = Course.class, entry = "course",inline=true)
    @Path("courses")
    private List<Course> courses;
}

@Getter
@Setter
@ToString
class Course {
    @Element(name = "cname", required = false)
    private String cname;
}
 类似资料: