当前位置:编程学习 > JAVA >>

急!用Java实现XML与关系数据类型的互换,求代码!

追问:请问这个具体怎么运行啊,好像把代码代入到Edipse里不能运行啊,是不是没main函数啊
答案:/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLUtil {

    public List<Object> ReadXML(Class c, String filename) {
        List<Object> videoList = new ArrayList<Object>();
        try {
            Document doc = read(filename);  //将Books.xml文档加载到加内中并放入doc中
            videoList = invoke(c, doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return videoList;
    }

    public List<Object> ReadXML(Class c, InputStream iput) {
        List<Object> videoList = new ArrayList<Object>();
        try {
            Document doc = read(iput);  //将Books.xml文档加载到加内中并放入doc中
            videoList = invoke(c, doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return videoList;
    }

    public List<Object> ReadXML(Class c, File file) {
        List<Object> videoList = new ArrayList<Object>();
        try {
            Document doc = read(file);  //将Books.xml文档加载到加内中并放入doc中
            videoList = invoke(c, doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return videoList;
    }

    private Document read(InputStream iput) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            return db.parse(iput);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Document read(String filePath) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            return db.parse(new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Document read(File file) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            return db.parse(file);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private List<Object> invoke(Class c, Document document) {
        List<Object> videoList = new ArrayList<Object>();
        try {
            NodeList configList = document.getElementsByTagName(c.getSimpleName());
            for (int i = 0; i < configList.getLength(); i++) {
                Node n = configList.item(i);
                NodeList tempList = n.getChildNodes();
                Object o = c.newInstance();
                for (int j = 0; j < tempList.getLength(); j++) {
                    Node m = tempList.item(j);
                    if (m.getFirstChild() != null) {
                        o = invoke(o, m.getNodeName(), m.getFirstChild().getNodeValue());
                    }
                }
                videoList.add(o);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return videoList;
    }

    private Object invoke(Object o, String fieldName, String value) {
        Class c = o.getClass();
        try {
            Class type = c.getDeclaredField(fieldName).getType();
            String methodName = "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
            Method ms = c.getMethod(methodName, type);
            if (type.getCanonicalName().equals("java.lang.String")) {
                ms.invoke(o, new Object[]{value});
            } else if (type.getCanonicalName().equals("int") || type.getCanonicalName().equals("java.lang.Integer")) {
                ms.invoke(o, new Object[]{new Integer(value)});
            } else if (type.getCanonicalName().equals("long") || type.getCanonicalName().equals("java.lang.Long")) {
                ms.invoke(o, new Object[]{new Long(value)});
            } else if (type.getCanonicalName().equals("boolean") || type.getCanonicalName().equals("java.lang.Boolean")) {
                ms.invoke(o, new Object[]{Boolean.valueOf(value)});
            } else if (type.getCanonicalName().equals("date") || type.getCanonicalName().equals("java.util.Date")) {
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                ms.invoke(o, new Object[]{sf.parse("")});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }

    public boolean creatXML(List list, String filePath) {
        try {
            //解析器工厂类
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //解析器
            DocumentBuilder builder = factory.newDocumentBuilder();
            //操作的Document对象
            Document document = builder.newDocument();
            document.setXmlStandalone(true);
            //设置XML的版本
            document.setXmlVersion("1.0");
            //创建根节点
            Element root = document.createElement("root");
            //将根节点添加到Document对象中
            document.appendChild(root);
            for (Object o : list) {
                root.appendChild(document.createTextNode("\n    "));//格式化xml
				//创建二级节点
                Element pageElement = document.createElement(o.getClass().getSimpleName());
                Field[] fields = o.getClass().getDeclaredFields();
                for (Field field : fields) {
                    String fieldName=field.getName();
                    String stringLetter=fieldName.substring(0, 1).toUpperCase();
                    //获得相应属性的getXXX方法名称
                    String getName="get"+stringLetter+fieldName.substring(1);
                    //获取相应的方法
                    Method getMethod=o.getClass().getMethod(getName, new Class[]{});
                    //调用源对象的getXXX()方法
                    Object value=null;
                    pageElement.appendChild(document.createTextNode("\n        ")); //格式化xml
                    //设置field.getName()节点
                    Element methodElement = document.createElement(field.getName());
                    //给method设置值
                    Class type = field.getType();
                    if(type.getCanonicalName().equals("date") || type.getCanonicalName().equals("java.util.Date")){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Object valueTemp  = getMethod.invoke(o, new Object[]{});
                        if(valueTemp!=null){
                            value=sdf.format(getMethod.invoke(o, new Object[]{}));
                        }
                    }else{
                        value=getMethod.invoke(o, new Object[]{});
                    }
                    if(value!=null){
                        methodElement.setTextContent(value.toString());
                    }
                    //添加field.getName()节点到二级节点内
                    pageElement.appendChild(methodElement);
                }
                pageElement.appendChild(document.createTextNode("\n    ")); //格式化xml
                //将二级节点段加人根节点内
                root.appendC

上一个:java 控制台报错:求对报错的解释。 我屏蔽了一条语句:然后就报错了:类不是抽象的且没有覆盖 抽象方法。
下一个:今天不小心把JAVA文件夹里所有的文件都给删了,现在下了JAVA程序可以安装,但是安装后打开就显示空白

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,