xml 字段解析
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.annotation.SuppressLint;
public class XmlToolW3CAndroid {
private static XmlToolW3CAndroid instance = new XmlToolW3CAndroid();
private XmlToolW3CAndroid() {
}
public static XmlToolW3CAndroid getInstance() {
return instance;
}
public Object toBean(String file, Class<?> clz, Object src) {
if (!StringTool.isNull(file) && new File(file).exists()) {
try {
return toBean(new FileInputStream(file), clz, src);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public Object toBean(InputStream is, Class<?> clz, Object src) {
try {
return toBean(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is).getDocumentElement(), clz,
src);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public Object toBean(InputStream is, Class<?> clz) {
try {
return toBean(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is).getDocumentElement(),
clz);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Parse the element to generate an instance of a class named clz. If the
* src is not null, just update its property. Recursion has been considered.
*
* @param e
* @param clz
* @param src
*
* @return
*/
@SuppressLint("DefaultLocale")
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object toBean(Element e, Class<?> clz, Object src) {
if (src == null) {
if (clz == null) {
return null;
}
try {
src = clz.newInstance();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
clz = src.getClass();
}
NodeList nodeList = e.getChildNodes();
List<Element> eList = new ArrayList<Element>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
eList.add((Element) n);
}
}
for (Element e1 : eList) {
String name = e1.getNodeName();
Field f = null;
List<Field> fs = new ArrayList<Field>();
for (Field field : clz.getDeclaredFields()) {
fs.add(field);
}
for (Field field : clz.getSuperclass().getDeclaredFields()) {
fs.add(field);
}
for (Field field : fs) {
field.setAccessible(true);
if (field.getName().toLowerCase().equals(name.toLowerCase())) {
f = field;
}
}
if (f != null) {
try {
Class<?> eleClz = null;
if (f.getType() == List.class) {
List list = (List) f.get(src);
if ((eleClz = (Class<?>) ((ParameterizedType) f.getGenericType())
.getActualTypeArguments()[0]) != String.class) {
nodeList = e1.getChildNodes();
List<Element> eList2 = new ArrayList<Element>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE
&& (n.getNodeName().trim().equals(eleClz.getSimpleName()) || n.getNodeName()
.equals(StringTool.firstCharLow(eleClz.getSimpleName(), true)))) {
eList2.add((Element) n);
}
}
for (Element e2 : eList2) {
list.add(toBean(e2, eleClz, null));
/*System.out.println("class name:" + eleClz.getSimpleName() + "data :"
+ e2.getAttribute("data" + "\t " + e2.getLocalName()));*/
}
} else {
String content = e1.getTextContent().trim();
if (content.startsWith("[") && content.endsWith("]")) {
String[] ss = content.substring(1, content.length() - 1).split(",");
for (String s : ss) {
list.add(s.trim());
}
}
}
}
else if (f.getType() == String.class) {
f.set(src, e1.getTextContent().trim());
} else if (f.getType().isPrimitive()) {
String s = e1.getChildNodes().item(0).getNodeValue().trim();
if (f.getType() == int.class) {
f.set(src, Integer.valueOf(s));
} else if (f.getType() == long.class) {
f.set(src, Long.valueOf(s));
} else if (f.getType() == float.class) {
f.set(src, Float.valueOf(s));
} else if (f.getType() == double.class) {
f.set(src, Double.valueOf(s));
} else if (f.getType() == boolean.class) {
f.set(src, s.toLowerCase().equals("true") ? true : false);
}
} else if (f.getType() != byte[].class) {
f.set(src, toBean(e1, f.getType(), null));
}
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
return src;
}
/***
* Convert XML into class object
*
* @param e
* XML
* @param clz
* class object
* @return class object
*/
@SuppressWarnings({ "unchecked", "null", "rawtypes" })
@SuppressLint("DefaultLocale")
public Object toBean(Element e, Class<?> clz) {
Object obj = null;
try {
obj = clz.newInstance();
} catch (Exception e2) {
e2.printStackTrace();
}
// get node
NodeList nodeList = e.getChildNodes();
List<Element> eList = new ArrayList<Element>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
eList.add((Element) n);
}
}
List<Field> fs = new ArrayList<Field>();
// Current class member variable
for (Field field : clz.getDeclaredFields()) {
fs.add(field);
}
// Parent class member variable
for (Field field : clz.getSuperclass().getDeclaredFields()) {
fs.add(field);
}
for (Element element : eList) {
Field f = null;
String nodeValue = "";
String name = "";
try{
nodeValue = element.getChildNodes().item(0).getTextContent();
name = element.getNodeName();}
catch(Exception ex)
{
//handle null pointer exception
/*try {
f.set(obj, "");
} catch (IllegalAccessException | IllegalArgumentException e1) {
// Setting member data failed
}*/
continue;
}
for(Field field: fs)
{
field.setAccessible(true);
if (field.getName().toLowerCase().equals(name.toLowerCase())) {
f = field;
}
}
if(f == null)
{
continue;
}
try {
if (f.getType() == String.class) {
f.set(obj, nodeValue);
} else if (f.getType() == int.class) {
f.set(obj, Integer.valueOf(nodeValue));
} else if (f.getType() == long.class) {
f.set(obj, Long.valueOf(nodeValue));
} else if (f.getType() == float.class) {
f.set(obj, Float.valueOf(nodeValue));
} else if (f.getType() == double.class) {
f.set(obj, Double.valueOf(nodeValue));
} else if (f.getType() == boolean.class) {
f.set(obj, nodeValue.toLowerCase().equals("true") ? true : false);
} else if (f.getType() == ArrayList.class || f.getType() == List.class) {
//Recursive function
List child = new ArrayList();
Class<?> eleClz = null;//child class object
NodeList nodeList1 = null;//list of child
if ((eleClz = (Class<?>) ((ParameterizedType) f.getGenericType())
.getActualTypeArguments()[0]) != String.class) {
nodeList1 = element.getChildNodes();
//total of childNote
for (int i = 0; i < nodeList1.getLength(); i++) {
//child list of data
try{
Node n = nodeList1.item(i);// object
Element childElement = (Element)n;
Object childObject = getObject(childElement,eleClz);
child.add(childObject);
}catch(Exception ex2)
{
//ex2.printStackTrace();
continue;
}
}
f.set(obj,child );
}
}
} catch (Exception e2) {
//e2.printStackTrace();
return obj;
}
}
return obj;
}
@SuppressWarnings("unchecked")
@SuppressLint("DefaultLocale")
public Object getObject(Element e, Class<?> clz)
{
Object obj = null;//child class object
//NodeList nodeList1 = null;//list of child
try{
obj = clz.newInstance();
}
catch(Exception ex)
{
}
// get node
NodeList nodeList = e.getChildNodes();
List<Element> eList = new ArrayList<Element>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
eList.add((Element) n);
}
}
List<Field> fs = new ArrayList<Field>();
// Current class member variable
for (Field field : clz.getDeclaredFields()) {
fs.add(field);
}
for (Element element : eList) {
Field f = null;
String nodeValue = "";
String name = "";
try{
nodeValue = element.getChildNodes().item(0).getTextContent();
name = element.getNodeName();}
catch(Exception ex)
{
continue;
}
for(Field field: fs)
{
field.setAccessible(true);
if (field.getName().toLowerCase().equals(name.toLowerCase())) {
f = field;
}
}
if(f == null)
{
continue;
}
try {
if (f.getType() == String.class) {
f.set(obj, nodeValue);
} else if (f.getType() == int.class) {
f.set(obj, Integer.valueOf(nodeValue));
} else if (f.getType() == long.class) {
f.set(obj, Long.valueOf(nodeValue));
} else if (f.getType() == float.class) {
f.set(obj, Float.valueOf(nodeValue));
} else if (f.getType() == double.class) {
f.set(obj, Double.valueOf(nodeValue));
} else if (f.getType() == boolean.class) {
f.set(obj, nodeValue.toLowerCase().equals("true") ? true : false);
} else if (f.getType() == ArrayList.class || f.getType() == List.class) {
//Recursive function
@SuppressWarnings("rawtypes")
List child = new ArrayList();
Class<?> eleClz = null;//child class object
NodeList nodeList2 = null;//list of child
if ((eleClz = (Class<?>) ((ParameterizedType) f.getGenericType())
.getActualTypeArguments()[0]) != String.class) {
nodeList2 = element.getChildNodes();
//total of childNote
for (int i = 0; i < nodeList2.getLength(); i++) {
//child list of data
try{
Node n = nodeList2.item(i);// object
Element childElement = (Element)n;
Object childObject = getObject(childElement,eleClz);
child.add(childObject);
}catch(Exception ex2)
{
//ex2.printStackTrace();
continue;
}
}
f.set(obj,child );
}
}
}catch(Exception e2)
{
}
}
return obj;
}
public String toXml(Object o) {
return toXml(o, null);
}
/**
* transform the bean to XML content
*
* @param o
* @param clzPropMapping
* the property of the bean class which needs to participate the
* transforming job. If it is null or empty, all the properties
* participate. Recursion has been considered.
* @return
*/
public String toXml(Object o, Map<Class<?>, List<String>> clzPropMapping) {
try {
if (o != null) {
StringBuffer buf = new StringBuffer();
Class<?> clz = o.getClass();
List<String> prop = null;
List<String> allProp = new ArrayList<String>();
for (Field f : clz.getDeclaredFields()) {
f.setAccessible(true);
allProp.add(f.getName());
}
if (clzPropMapping != null) {
prop = clzPropMapping.get(clz);
if (prop == null || prop.isEmpty()) {
prop = allProp;
}
} else {
prop = allProp;
}
buf.append("<" + clz.getSimpleName() + ">");
for (String p : prop) {
Field f = clz.getDeclaredField(p);
f.setAccessible(true);
Object oProp = f.get(o);
if (oProp != null) {
buf.append("<" + p + ">");
if (f.getType() == List.class) {
if (((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0] != String.class) {
List<?> list = (List<?>) oProp;
for (Object e : list) {
String s = toXml(e, clzPropMapping);
if (!StringTool.isNull(s)) {
buf.append(s);
}
}
} else {
buf.append(oProp.toString());
}
} else if (f.getType().isPrimitive() || f.getType() == String.class) {
String value = "";
if (!oProp.equals("")) {
value = oProp.toString();
value = StringTool.becomeXmlSpecialChar(value);
}
buf.append(value);
} else {
String s = toXml(oProp, clzPropMapping);
/**
* delete the prop's clz.getSimpleName() tag
*/
if (!StringTool.isNull(s)) {
s = s.substring(s.indexOf('>') + 1, s.lastIndexOf('<'));
buf.append(s);
}
}
buf.append("</" + p + ">");
}
}
buf.append("</" + clz.getSimpleName() + ">");
return buf.toString();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
测试案例
User mUser = (User) XmlToolW3CAndroid.getInstance().toBean(new ByteArrayInputStream(xml字符串), User.class,null);
public class User{
private String name;
private int age;
}
{user:{name:“tom”,age:12}}