注解实现xml转bean bean转xml,xstream

//转化工具类
public class XmlUtil{
    /**
     * java 转换成xml
     * @Title: toXml
     * @Description: TODO
     * @param obj 对象实例
     * @return String xml字符串
     */
    public static String toXml(Object obj){
        XStream xstream=new XStream();
//          XStream xstream=new XStream(new DomDriver()); //直接用jaxp dom来解释
//          XStream xstream=new XStream(new DomDriver("utf-8")); //指定编码解析器,直接用jaxp dom来解释

        如果没有这句,xml中的根元素会是<包.类名>;或者说:注解根本就没生效,所以的元素名就是类的属性
        xstream.processAnnotations(obj.getClass()); //通过注解方式的,一定要有这句话
        return xstream.toXML(obj);
    }

    /**
     *  将传入xml文本转换成Java对象
     * @Title: toBean
     * @Description: TODO
     * @param xmlStr
     * @param cls  xml对应的class类
     * @return T   xml对应的class类的实例对象
     *
     * 调用的方法实例:PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
     */
    public static <T> T  toBean(String xmlStr,Class<T> cls){
        //注意:不是new Xstream(); 否则报错:java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserFactory
        XStream xstream=new XStream(new DomDriver());
        xstream.processAnnotations(cls);
        T obj=(T)xstream.fromXML(xmlStr);
        return obj;
    }

    /**
     * 写到xml文件中去
     * @Title: writeXMLFile
     * @Description: TODO
     * @param obj 对象
     * @param absPath 绝对路径
     * @param fileName  文件名
     * @return boolean
     */

    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) {
//                log.error("创建{"+ filePath +"}文件失败!!!" + Strings.getStackTrace(e));
                return false ;
            }
        }// end if
        OutputStream ous = null ;
        try {
            ous = new FileOutputStream(file);
            ous.write(strXml.getBytes());
            ous.flush();
        } catch (Exception e1) {
//            log.error("写{"+ filePath +"}文件失败!!!" + Strings.getStackTrace(e1));
            return false;
        }finally{
            if(ous != null )
                try {
                    ous.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return true ;
    }

    /**
     * 从xml文件读取报文
     * @Title: toBeanFromFile
     * @Description: TODO
     * @param absPath 绝对路径
     * @param fileName 文件名
     * @param cls
     * @throws Exception
     * @return T
     */
    public static <T> T  toBeanFromFile(String absPath, String fileName,Class<T> cls) throws Exception{
        String filePath = absPath +fileName;
        InputStream ins = null ;
        try {
            ins = new FileInputStream(new File(filePath ));
        } catch (Exception e) {
            throw new Exception("读{"+ filePath +"}文件失败!", e);
        }

//        String encode = useEncode(cls);
//        String encode = useEncode(cls);
        XStream xstream=new XStream(new DomDriver());
        xstream.processAnnotations(cls);
        T obj =null;
        try {
            obj = (T)xstream.fromXML(ins);
        } catch (Exception e) {
            throw new Exception("解析{"+ filePath +"}文件失败!",e);
        }
        if(ins != null)
            ins.close();
        return obj;
    }

}
@XStreamAlias("book")
public class Book {
    @XStreamAlias("title")
    private String title;
    @XStreamAlias("author")
    private String author;
    @XStreamAlias("content")
    private String content;
    @XStreamAlias("chapters")
    private List<Chapter> chapters;
@XStreamAlias("chapter")
public class Chapter {
    @XStreamAlias("chapterNum")
    private String chapterNum;
    @XStreamAlias("chapterName")
    private String chapterName;
    @XStreamAlias("chapterContent")
    private String chapterContent;
    @XStreamAlias("classicals")
    private List<Classical> classicals;
@XStreamAlias("classical")
public class Classical {
    @XStreamAlias("classicalCode")
    private String classicalCode;
    @XStreamAlias("classicalContent")
    private String classicalContent;
public class BookTestToBean {
    public static void main(String[] args) throws Exception {
        String xlmPath = "E:/resource/data/";
        Book newBook = new Book();
        newBook.setTitle("钢铁是怎样练成的");
        newBook.setAuthor("尼·奥斯特洛夫斯基");
        List<Chapter> chapters = new ArrayList<>();
        for(int i = 0; i<10; i++){
            Chapter chapter = new Chapter();
            StringBuffer content = new StringBuffer();
            content.append("“节前上我家去补考的,都给我站起来!”一个脸皮松弛的胖神甫,身上穿着法衣,脖子上挂着沉甸甸的十字架,气势汹汹地瞪着全班的学生。");
            content.append("六个学生应声从板凳上站了起来,四个男生,两个女生。神甫两只小眼睛闪着凶光,像要把他们一口吞下去似的。孩子们惊恐不安地望着他。");
            content.append("“你们俩坐下。”神甫朝女孩子挥挥手说。她们急忙坐下,松了一口气。瓦西里神甫那对小眼睛死盯在四个男孩子身上。“过来吧,宝贝们!”瓦西里神甫站起来,推开椅子,走到挤作一团的四个孩子跟前。");
            content.append("“你们这几个小无赖,谁抽烟?”四个孩子都小声回答:“我们不会抽,神甫。”神甫脸都气红了。“混帐东西,不会抽,那发面里的烟末是谁撒的?都不会抽吗?好,咱们这就来看看!把口袋翻过来,快点!听见了没有?快翻过来!”");
            content.append("三个孩子开始把他们口袋里的东西掏出来,放在桌子上。");
            chapter.setChapterContent(content.toString());
            chapter.setChapterName("第"+(i+1)+"章");
            chapter.setChapterNum((i+1)+"");
            List<Classical> classicals = new ArrayList<>();
            for(int n=0;n<4;n++){
                Classical classical = new Classical();
                classical.setClassicalCode("知识点:"+n);
                classical.setClassicalContent(content.toString());
                classicals.add(classical);
            }
            chapter.setClassicals(classicals);
            chapters.add(chapter);
        }
        newBook.setChapters(chapters);
        XmlUtil.toXMLFile(newBook,xlmPath,"newbook.xml");
        File file = new File(xlmPath);
        if (!file.exists()) {
            System.err.println(xlmPath+":该文件不存在!");
            return;
        }
        Book book = XmlUtil.toBeanFromFile(xlmPath,"newbook.xml",Book.class);
        System.out.println(book.getAuthor());
        System.out.println(book.getTitle());
        if(book.getChapters() != null){
            book.getChapters().forEach(chapter->{
                System.out.println(chapter.getChapterNum()+"-"+chapter.getChapterName()+"-");
                if(chapter.getClassicals() != null){
                    chapter.getClassicals().forEach(classical -> {
                        System.out.println(classical.getClassicalCode()+"-"+classical.getClassicalContent());
                    });
                }
            });
        }

//        Book book = XmlUtil.toBean(new FileReader(file),Book.class);
    }
}

 

<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.2.1</version>
</dependency>

转载于:https://my.oschina.net/wugong/blog/1540830

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值