Java 怎么将Java bean转换为XML

2019年8月9日22:20:21Java 怎么将Java bean转换为XML已关闭评论 393 1170字阅读3分54秒

1.简介

Java 怎么将Java bean转换为XML?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.ParserConfigurationException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {

    public static Element beanToXml(Document document, Object obj)
            throws ParserConfigurationException, InvocationTargetException,
            IllegalAccessException {
        String name = obj.getClass().getName();
        Element rootElement = document.createElement(name);
        Method[] methods = obj.getClass().getMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            String methodName = method.getName();
            String fieldName = analyzeFieldName(methodName);
            Element fieldElement = document.createElement(fieldName);
            if (methodName.startsWith("get")
                    && !"getClass".equals(methodName)) {
                Object value = method.invoke(obj);
                if (value != null && !"".equals(value.toString())) {
                    fieldElement.setTextContent(value.toString());
                } else {
                    continue;
                }
            } else {
                continue;
            }
            rootElement.appendChild(fieldElement);
        }
        return rootElement;
    }

    private static String analyzeFieldName(String methodName) {
        return String.valueOf(methodName.charAt(3)).toLowerCase()
                + methodName.substring(4, methodName.length());
    }
}

 
继续阅读
编程十万个怎么办