Java examples for XML:XML Java Bean
Convert Java bean To Xml
//package com.java2s; 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; }//from w ww. jav a 2 s . com } 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()); } }