1, jar 包
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>xom</groupId> <artifactId>xom</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.31</version> </dependency>
2, Tools
Package Comkjbfakutil; import com.alibaba.fastjson.JSONObject; import net.sf.json.xml.XMLSerializer; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; /********************************* * Class Description: * @author huangsz * @date 2019/11/20 * @version v1.0 **********************************/ public class XmlUtil { public static Object xmlToBean (the Element rootElt, Class pojo) throws Exception { // was first defined field pojo Field, [] = Fields pojo.getDeclaredFields (); // dynamically generated object from pojo passed Class Object obj = pojo. newInstance (); for (field, field,: fields) { // set the field can access (must be, otherwise an error) field.setAccessible ( to true ); // get the field attribute name String name = field.getName (); // this If the field for a role is not present in the Element will throw an exception if the exception is skipped. the try { rootElt.elementTextTrim(name); } catch (Exception ex) { continue; } IF (rootElt.elementTextTrim (name)! = null &&! "" .equals (rootElt.elementTextTrim (name))) { // The type of the field values converted to the corresponding type, and disposed to the object generated. IF (Field.getType (). the equals (Long. class ) || Field.getType (). the equals ( Long . class )) { field.set(obj, Long.parseLong(rootElt.elementTextTrim(name))); } else if (field.getType().equals(String.class)) { field.set(obj, rootElt.elementTextTrim(name)); } else if (field.getType().equals(Double.class) || field.getType().equals(double.class)) { field.set(obj, Double.parseDouble(rootElt.elementTextTrim(name))); } else if (field.getType().equals(Integer.class) || field.getType().equals(int.class)) { field.set(obj, Integer.parseInt(rootElt.elementTextTrim(name))); } else if (field.getType().equals(java.util.Date.class)) { field.set(obj, Date.parse(rootElt.elementTextTrim(name))); } else { continue; } } } return obj; } public static <T> T xmlToBean(String xml,Class<T> clazz) { T t = null; try { List<T> ts = xmlToList(xml, clazz); if (!ts.isEmpty()) { t = ts.get(0); } } catch (Exception e) { e.printStackTrace (); System.out.println ( "data analysis error" ); } return t; } /** * DMO4J write XML * @Param obj generic objects * @Param List entityPropertys collection of generic objects * / public static <T> String beanToXml (T obj, List <T> entityPropertys) { // detection efficiency Long lasting = System.currentTimeMillis (); String xmlStr = null; try { Document the Document = DocumentHelper.createDocument (); // get class name String RootName = obj.getClass () getSimpleName ();. // Add the root node the Element document.addElement the root = (RootName + "S" ); // get entity class All attributes Field, [] = properties . obj.getClass () getDeclaredFields (); // recursive entity for (T T: entityPropertys) { // two nodes the Element secondRoot = root.addElement (RootName); for ( int i = 0; i < properties.length; i++) { // 反射get方法 Method meth = t.getClass().getMethod( "get" + properties[i].getName().substring(0, 1) .toUpperCase() Properties + [I] .getName () the substring (. 1. )); // add two nodes attribute, attribute value corresponding to the value of an attribute secondRoot.addElement (properties [i] .getName ( )) setText (. meth.invoke(t).toString()); } } xmlStr = document.asXML(); System.out.println("document字符串"+xmlStr); long lasting2 = System.currentTimeMillis(); System.out.println ( "write XMLtoString end, when using" + (lasting2 - lasting) + "MS" ); } catch (Exception e) { System.out.println ( "XML file write failed" ); e.printStackTrace (); } return xmlStr; } /** * * @Param path and address XMLPathAndName XML file * @Param t generic objects * @return */ public static <T> List<T> xmlToList(String XMLPathAndName, Class<T> t) { long lasting = System.currentTimeMillis(); List<T> list = new ArrayList<>(); try { DOC the Document = DocumentHelper.parseText (XMLPathAndName); // get the root node of the Element = the root doc.getRootElement (); // two nodes Element foo; I iterator = root.elementIterator (); the while (i.hasNext ()) { // the next two nodes foo = (the Element) i.next (); T t2 = (T)xmlToBean(foo, t); list.add(t2); } } catch (Exception e) { e.printStackTrace (); } long lasting2 = System.currentTimeMillis(); System.out.println ( "read XMLtoString end, when using" + (lasting2 - lasting) + "MS" ); return List; } public static JSONObject xml2Json(String xml){ XMLSerializer xmlSerializer = new XMLSerializer(); String read = xmlSerializer.read(xml).toString(); return JSONObject.parseObject(read); } public static String json2Xml(net.sf.json.JSONObject json, String rootName) throws DocumentException { String sXml = ""; XMLSerializer xmlSerializer = new XMLSerializer(); xmlSerializer.setTypeHintsEnabled(false); xmlSerializer.setRootName(rootName); String sContent = xmlSerializer.write(json,"utf-8"); try { Document docCon = DocumentHelper.parseText(sContent); SXML = docCon.getRootElement () asXML (),.; } catch (DocumentException e) { e.printStackTrace (); } return sXml; } }
3, testing and certification
javaBean categories:
public class TestBean { private int id; private String dealTime; private String status; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDealTime() { return dealTime; } public void setDealTime(String dealTime) { this.dealTime = dealTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "TestBean{" + "id=" + id + ", dealTime='" + dealTime + '\'' + ", status='" + status + '\'' + '}'; } }
Package Comkjbfakutil; import com.alibaba.fastjson.JSONObject; import java.util.List; /********************************* * Class Description: * @author huangsz * @date 2019/11/20 * @version v1.0 **********************************/ public class App { public static void readXml() { try { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<TestBeans>" + "<TestBean><id>1</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" + // "<TestBean><id>2</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" + // "<TestBean><id>3</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" + // "<TestBean><id>4</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" + // "<TestBean><id>5</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" + "</TestBeans>"; List<TestBean> list = XmlUtil.xmlToList(xml, TestBean.class); System.out.println("list = " + list.size()); for (TestBean bean : list) { System.out.println(bean); } TestBean bean = XmlUtil.xmlToBean(xml, TestBean.class); System.out.println(bean); JSONObject jsonObject = XmlUtil.xml2Json(xml); System.out.println(jsonObject); // String str = "{\"TestBean\":{\"dealTime\":\"20070510165424\",\"id\":\"1\",\"status\":\"2\"}}"; net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(str); String testBeans = XmlUtil.json2Xml(fromObject, "TestBeans"); System.out.println(testBeans); TestBean bean1 = XmlUtil.xmlToBean (test beans, TestBean. Class ); System.out.println(bean1); } catch (Exception e) { e.printStackTrace (); } } public static void main(String[] args) { readXml(); } }