jaxb解析xml遇到的问题

前端之家收集整理的这篇文章主要介绍了jaxb解析xml遇到的问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

之前使用jaxb来解析webservice返回的xml,由于xml的格式总是会出现意想不到的变化,导致xml格式通过不了jaxb解析而报错,现已放弃jaxb解析,记录下下来自己是怎么修改的,
首先用于转换接收到的xml格式的 串的工具类,在接下来的通信:
public class XmlTranslator {

@SuppressWarnings("unchecked")
public static List<Map<Object,Object>> readXml(String xmlStr) throws Exception{
    Document doc = null;

    List<Map<Object,Object>> list = null;
    try {
        list = new ArrayList<Map<Object,Object>>();
        doc = DocumentHelper.parseText(xmlStr); // 将字符串转为XML
        Element rootElement = doc.getRootElement();
        System.out.println(rootElement.toString());
        Iterator<Element> ite = rootElement.elements().iterator();
        while (ite.hasNext()) {
            Element element = (Element) ite.next();
            Map<Object,Object> map = traversingTree(element);
            if (map.size() == 0)
                continue;
            list.add(map);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}

public static Map<Object,Object> traversingTree(Element element) {
    Map<Object,Object> map = new ConcurrentHashMap<Object,Object>();
    for (int i = 0,size = element.nodeCount(); i < size; i++) {
        Node node = element.node(i);
        if (node instanceof Element) {
            traversingTree((Element) node);
            map.put(node.getName(),node.getText());
        }
    }
    return map;
}

}
接下来使用上面工具类开始解析过程

public abstract class Xml2Object {
private Class clazz;

@SuppressWarnings({ "unchecked","rawtypes" })
public Xml2Object() {
    Type genType = getClass().getGenericSuperclass();
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    clazz = (Class) params[0];
}

public List<T> getObjectCollection(String xmlStr) {
    List<Map<Object,Object>> list = null;
    try {
        list = XmlTranslator.readXml(xmlStr);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    if (Assert.isEmpty(list))
        return null;
    List<T> collection = new ArrayList<T>();
    try {
        T entity = null;
        Field[] fields = clazz.getDeclaredFields();
        for (Map<Object,Object> map : list) {
            entity = clazz.newInstance();
            for (Field field : fields) {
                String fieldName = field.getName();
                String setMethodName = "set"
                        + fieldName.substring(0,1).toUpperCase()
                        + fieldName.substring(1);
                XmlElement element = field.getAnnotation(XmlElement.class);

                String elementName = element.name();
                Object elementValue = null;
                Class<?> type = field.getType();

                Method method = clazz.getMethod(setMethodName,type);

                if (!"##default".equals(elementName)) {
                    elementValue = map.get(elementName);
                } else {
                    elementValue = map.get(fieldName);
                }
                method.invoke(entity,type.cast(elementValue));

            }

            collection.add(entity);
        }

    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return collection;
}

}
通过继承上面的抽象类完成对具体类
public class XML2User extends Xml2Object{

}

User:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = “USER”)
public final class User{
@XmlElement(name = “name”,required = true)
protected String name;
@XmlElement(name = “department”,required = true)
protected String department;
@XmlElement(name = “cert”,required = true)
protected String cert;

//get、set省略

} 测试 @Test public void main(){ String xml=”something”; Xml2Object visitorUtil = new Xml2User(); List infos = visitorUtil.getObjectCollection(xml); }

猜你在找的XML相关文章