使用XMLEncoder/XMLDecoder和DocumentBuilder实现XML和String互相转换

package com.micsay;

import java.util.*;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
public class Student{
    private String name;
    private int age;
    public Student(){}

    public Student(String n, int a){
        name = n;
        age = a;
    }
    public void setName(String n){
        name = n;
    }
    public void setAge(int a){
        age = a;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
    public String toString(){
        return name + age;
    }
    public static String toXmlByXMLEncoder(List<Student> stu){
        ByteArrayOutputStream os = new ByteArrayOutputStream(10000);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        XMLEncoder xe = new XMLEncoder(bos);
        for(Student tmp : stu)
            xe.writeObject(tmp);
        xe.flush();//write out
        xe.close();//这个地方要注意,如果不在这里关闭,就不能完整输出(“</java>”不会被输出)
        String s = os.toString();
        try{
            if(bos != null)
                bos.close();
        }catch(IOException e){

        }
        return s;
    }

    public static String toXml(Student stu){
        StringBuilder sbuilder = new StringBuilder("<student>");
        sbuilder.append("<name>");
        sbuilder.append(stu.name);
        sbuilder.append("</name>");
        sbuilder.append("<age>");
        sbuilder.append(stu.age);
        sbuilder.append("</age>");
        sbuilder.append("</student>");
        return sbuilder.toString();
    }
    public static List<Student> fromXmlByXMLDecoder(String s){
        ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes());
        BufferedInputStream is = new BufferedInputStream(bis);
        XMLDecoder xd = new XMLDecoder(is);
        List<Student> list = new ArrayList<Student>();
        try{
            Object obj;
            try{
                while((obj = xd.readObject()) != null){
                    list.add((Student)obj);
                }
            }catch(ArrayIndexOutOfBoundsException e){

            }

            if(is != null)
                is.close();
            if(xd != null)
                xd.close();
        }catch(IOException e){
        }
        return list;
    }
    public static List<Student> fromXml(String s){
        List<Student> slist = new ArrayList<Student>();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        StringReader sr = null;
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            sr = new StringReader(s);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);
            Element root = document.getDocumentElement();
            NodeList students = root.getElementsByTagName("student");
            for (int i=0,leni=students.getLength(); i < leni; i++) {
                Node student = students.item(i);
                Student  stu = new Student();
                NodeList studentInfo = student.getChildNodes();
                for (int j=0,lenj=studentInfo.getLength(); j<lenj; j++) {
                    Node node = studentInfo.item(j);
                    if("name".equals(node.getNodeName().toString())){
                        stu.setName(node.getTextContent());
                    }else if("age".equals(node.getNodeName().toString())){
                        stu.setAge(Integer.valueOf(node.getTextContent()));
                    }
                }
                slist.add(stu);
            }
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        } catch (SAXException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally{
            if(sr != null)sr.close();
            return slist;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值