精华内容
下载资源
问答
  • Object转xml或xml转Object

    2015-04-06 20:24:59
    Object转xml之间的映射组装,xml转Object之间的映射解析
  • Object转XML && XML转Object

    千次阅读 2015-04-06 20:12:02
    对象转xml或xml转对象

    Object转XML && XML转Object 测试类:

    package com.insist.objectxml;
    
    import com.insist.objectxml.common.JaxbMapper;
    import com.insist.objectxml.person.Body;
    import com.insist.objectxml.person.Person;
    
    /**
     * 描述:测试对象——>XML || XML——>对象<br>
     * 作者:liqijing <br>
     * 修改日期:2015-4-6下午07:38:17 <br>
     * E-mail: lijinginsistsmile@163.com <br>
     */
    public class ObjectXml {
    	
    	
    	public static void main(String[] args) {
    		String reqXml = getXml();
    		System.out.println("输出XML:"+"\n"+reqXml);
    		
    		System.out.println("解析XML-->Object"+"===========================================");
    		Person person = getPerson(reqXml);
    		System.out.println("id="+person.getPerId()+",name="+person.getPerName()+",age="+person.getPerAge()+",sex="+person.getPerSex()+",email="+person.getEmail());
    	}
    	
    	
    	/**
    	 * 方法名称: getXml<br>
    	 * 描述: Object --> XML
    	 * 作者: liqijing
    	 * 修改日期:2015-4-6下午07:46:03
    	 * @param body
    	 * @param encoding
    	 * @return
    	 */
    	public static String getXml(){
    		Body body = new Body();
    		body.setPerson(initPerson());
    		String reqXml = JaxbMapper.toXml(body, "GBK") ;
    		if(reqXml == null){
    			return "组装XML出错!" ; 
    		}
    		return reqXml ;
    	}
    	
    	
    	/**
    	 * 方法名称: getPerson<br>
    	 * 描述:XML ---> Object
    	 * 作者: liqijing
    	 * 修改日期:2015-4-6下午07:47:21
    	 * @param reqXml
    	 * @return
    	 */
    	public static Person getPerson(String reqXml){
    		Body body = JaxbMapper.fromXml(reqXml, Body.class) ;
    		return body.getPerson() ;
    		
    	}
    	
    	
    	/**
    	 * 方法名称: initPerson<br>
    	 * 描述:初始化person对象
    	 * 作者: liqijing
    	 * 修改日期:2015-4-6下午07:38:12
    	 * @return
    	 */
    	public static Person initPerson(){
    		Person person = new Person("100000","马云","24","男","lijinginsistsmile@163.com");
    		return person ;
    	}
    	
    }
    

    JaxbMapper生成&&解析:

    /*******************************************************************************
     * Copyright (c) 2005, 2014 springside.github.io
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     *******************************************************************************/
    package com.insist.objectxml.common;
    
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.util.Collection;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentMap;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBElement;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    import javax.xml.bind.annotation.XmlAnyElement;
    import javax.xml.namespace.QName;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.commons.lang3.Validate;
    
    import com.insist.objectxml.exception.Exceptions;
    
    
    /**
     * 使用Jaxb2.0实现XML<->Java Object的Mapper.
     * 
     * 在创建时需要设定所有需要序列化的Root对象的Class.
     * 特别支持Root对象是Collection的情形.
     * 
     * @author calvin
     */
    public class JaxbMapper {
    
    	private static final Exceptions Exceptions = null;
    	private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();
    
    	/**
    	 * Java Object->Xml without encoding.
    	 */
    	public static String toXml(Object root) {
    		Class clazz = Reflections.getUserClass(root);
    		return toXml(root, clazz, null);
    	}
    
    	/**
    	 * Java Object->Xml with encoding.
    	 */
    	public static String toXml(Object root, String encoding) {
    		Class clazz = Reflections.getUserClass(root);
    		return toXml(root, clazz, encoding);
    	}
    
    	/**
    	 * Java Object->Xml with encoding.
    	 */
    	public static String toXml(Object root, Class clazz, String encoding) {
    		try {
    			StringWriter writer = new StringWriter();
    			createMarshaller(clazz, encoding).marshal(root, writer);
    			return writer.toString();
    		} catch (JAXBException e) {
    			throw Exceptions.unchecked(e);
    		}
    	}
    
    	/**
    	 * Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
    	 */
    	public static String toXml(Collection<?> root, String rootName, Class clazz) {
    		return toXml(root, rootName, clazz, null);
    	}
    
    	/**
    	 * Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
    	 */
    	public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
    		try {
    			CollectionWrapper wrapper = new CollectionWrapper();
    			wrapper.collection = root;
    
    			JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName), CollectionWrapper.class, wrapper);
    
    			StringWriter writer = new StringWriter();
    			createMarshaller(clazz, encoding).marshal(wrapperElement, writer);
    
    			return writer.toString();
    		} catch (JAXBException e) {
    			throw Exceptions.unchecked(e);
    		}
    	}
    
    	/**
    	 * Xml->Java Object.
    	 */
    	public static <T> T fromXml(String xml, Class<T> clazz) {
    		try {
    			StringReader reader = new StringReader(xml);
    			return (T) createUnmarshaller(clazz).unmarshal(reader);
    		} catch (JAXBException e) {
    			throw Exceptions.unchecked(e);
    		}
    	}
    
    	/**
    	 * 创建Marshaller并设定encoding(可为null).
    	 * 线程不安全,需要每次创建或pooling。
    	 */
    	public static Marshaller createMarshaller(Class clazz, String encoding) {
    		try {
    			JAXBContext jaxbContext = getJaxbContext(clazz);
    
    			Marshaller marshaller = jaxbContext.createMarshaller();
    
    			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    
    			if (StringUtils.isNotBlank(encoding)) {
    				marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    			}
    
    			return marshaller;
    		} catch (JAXBException e) {
    			throw Exceptions.unchecked(e);
    		}
    	}
    
    	/**
    	 * 创建UnMarshaller.
    	 * 线程不安全,需要每次创建或pooling。
    	 */
    	public static Unmarshaller createUnmarshaller(Class clazz) {
    		try {
    			JAXBContext jaxbContext = getJaxbContext(clazz);
    			return jaxbContext.createUnmarshaller();
    		} catch (JAXBException e) {
    			throw Exceptions.unchecked(e);
    		}
    	}
    
    	protected static JAXBContext getJaxbContext(Class clazz) {
    		Validate.notNull(clazz, "'clazz' must not be null");
    		JAXBContext jaxbContext = jaxbContexts.get(clazz);
    		if (jaxbContext == null) {
    			try {
    				jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
    				jaxbContexts.putIfAbsent(clazz, jaxbContext);
    			} catch (JAXBException ex) {
    				throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex);
    			}
    		}
    		return jaxbContext;
    	}
    
    	/**
    	 * 封装Root Element 是 Collection的情况.
    	 */
    	public static class CollectionWrapper {
    
    		@XmlAnyElement
    		protected Collection<?> collection;
    	}
    }
    


    Reflections 类:

    /*******************************************************************************
     * Copyright (c) 2005, 2014 springside.github.io
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     *******************************************************************************/
    package com.insist.objectxml.common;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.commons.lang3.Validate;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * 反射工具类.
     * 
     * 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
     * 
     * @author calvin
     */
    public class Reflections {
    	private static final String SETTER_PREFIX = "set";
    
    	private static final String GETTER_PREFIX = "get";
    
    	private static final String CGLIB_CLASS_SEPARATOR = "$$";
    
    	private static Logger logger = LoggerFactory.getLogger(Reflections.class);
    
    	/**
    	 * 调用Getter方法.
    	 */
    	public static Object invokeGetter(Object obj, String propertyName) {
    		String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(propertyName);
    		return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
    	}
    
    	/**
    	 * 调用Setter方法, 仅匹配方法名。
    	 */
    	public static void invokeSetter(Object obj, String propertyName, Object value) {
    		String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(propertyName);
    		invokeMethodByName(obj, setterMethodName, new Object[] { value });
    	}
    
    	/**
    	 * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
    	 */
    	public static Object getFieldValue(final Object obj, final String fieldName) {
    		Field field = getAccessibleField(obj, fieldName);
    
    		if (field == null) {
    			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    		}
    
    		Object result = null;
    		try {
    			result = field.get(obj);
    		} catch (IllegalAccessException e) {
    			logger.error("不可能抛出的异常{}", e.getMessage());
    		}
    		return result;
    	}
    
    	/**
    	 * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
    	 */
    	public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
    		Field field = getAccessibleField(obj, fieldName);
    
    		if (field == null) {
    			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    		}
    
    		try {
    			field.set(obj, value);
    		} catch (IllegalAccessException e) {
    			logger.error("不可能抛出的异常:{}", e.getMessage());
    		}
    	}
    
    	/**
    	 * 直接调用对象方法, 无视private/protected修饰符.
    	 * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
    	 * 同时匹配方法名+参数类型,
    	 */
    	public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) {
    		Method method = getAccessibleMethod(obj, methodName, parameterTypes);
    		if (method == null) {
    			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
    		}
    
    		try {
    			return method.invoke(obj, args);
    		} catch (Exception e) {
    			throw convertReflectionExceptionToUnchecked(e);
    		}
    	}
    
    	/**
    	 * 直接调用对象方法, 无视private/protected修饰符,
    	 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
    	 * 只匹配函数名,如果有多个同名函数调用第一个。
    	 */
    	public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
    		Method method = getAccessibleMethodByName(obj, methodName);
    		if (method == null) {
    			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
    		}
    
    		try {
    			return method.invoke(obj, args);
    		} catch (Exception e) {
    			throw convertReflectionExceptionToUnchecked(e);
    		}
    	}
    
    	/**
    	 * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
    	 * 
    	 * 如向上转型到Object仍无法找到, 返回null.
    	 */
    	public static Field getAccessibleField(final Object obj, final String fieldName) {
    		Validate.notNull(obj, "object can't be null");
    		Validate.notBlank(fieldName, "fieldName can't be blank");
    		for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
    			try {
    				Field field = superClass.getDeclaredField(fieldName);
    				makeAccessible(field);
    				return field;
    			} catch (NoSuchFieldException e) {// NOSONAR
    				// Field不在当前类定义,继续向上转型
    			}
    		}
    		return null;
    	}
    
    	/**
    	 * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
    	 * 如向上转型到Object仍无法找到, 返回null.
    	 * 匹配函数名+参数类型。
    	 * 
    	 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
    	 */
    	public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) {
    		Validate.notNull(obj, "object can't be null");
    		Validate.notBlank(methodName, "methodName can't be blank");
    
    		for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
    			try {
    				Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
    				makeAccessible(method);
    				return method;
    			} catch (NoSuchMethodException e) {
    				// Method不在当前类定义,继续向上转型
    			}
    		}
    		return null;
    	}
    
    	/**
    	 * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
    	 * 如向上转型到Object仍无法找到, 返回null.
    	 * 只匹配函数名。
    	 * 
    	 * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
    	 */
    	public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
    		Validate.notNull(obj, "object can't be null");
    		Validate.notBlank(methodName, "methodName can't be blank");
    
    		for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
    			Method[] methods = searchType.getDeclaredMethods();
    			for (Method method : methods) {
    				if (method.getName().equals(methodName)) {
    					makeAccessible(method);
    					return method;
    				}
    			}
    		}
    		return null;
    	}
    
    	/**
    	 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
    	 */
    	public static void makeAccessible(Method method) {
    		if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
    			method.setAccessible(true);
    		}
    	}
    
    	/**
    	 * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
    	 */
    	public static void makeAccessible(Field field) {
    		if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
    			field.setAccessible(true);
    		}
    	}
    
    	/**
    	 * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
    	 * 如无法找到, 返回Object.class.
    	 * eg.
    	 * public UserDao extends HibernateDao<User>
    	 * 
    	 * @param clazz The class to introspect
    	 * @return the first generic declaration, or Object.class if cannot be determined
    	 */
    	public static <T> Class<T> getClassGenricType(final Class clazz) {
    		return getClassGenricType(clazz, 0);
    	}
    
    	/**
    	 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
    	 * 如无法找到, 返回Object.class.
    	 * 
    	 * 如public UserDao extends HibernateDao<User,Long>
    	 * 
    	 * @param clazz clazz The class to introspect
    	 * @param index the Index of the generic ddeclaration,start from 0.
    	 * @return the index generic declaration, or Object.class if cannot be determined
    	 */
    	public static Class getClassGenricType(final Class clazz, final int index) {
    
    		Type genType = clazz.getGenericSuperclass();
    
    		if (!(genType instanceof ParameterizedType)) {
    			logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
    			return Object.class;
    		}
    
    		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    
    		if ((index >= params.length) || (index < 0)) {
    			logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length);
    			return Object.class;
    		}
    		if (!(params[index] instanceof Class)) {
    			logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
    			return Object.class;
    		}
    
    		return (Class) params[index];
    	}
    
    	public static Class<?> getUserClass(Object instance) {
    		Validate.notNull(instance, "Instance must not be null");
    		Class clazz = instance.getClass();
    		if ((clazz != null) && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
    			Class<?> superClass = clazz.getSuperclass();
    			if ((superClass != null) && !Object.class.equals(superClass)) {
    				return superClass;
    			}
    		}
    		return clazz;
    
    	}
    
    	/**
    	 * 将反射时的checked exception转换为unchecked exception.
    	 */
    	public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
    		if ((e instanceof IllegalAccessException) || (e instanceof IllegalArgumentException) || (e instanceof NoSuchMethodException)) {
    			return new IllegalArgumentException(e);
    		} else if (e instanceof InvocationTargetException) {
    			return new RuntimeException(((InvocationTargetException) e).getTargetException());
    		} else if (e instanceof RuntimeException) {
    			return (RuntimeException) e;
    		}
    		return new RuntimeException("Unexpected Checked Exception.", e);
    	}
    }
    


    Person类

    package com.insist.objectxml.person;
    
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlType;
     
    /**
     * 描述:object转xml实体类<br>
     * 作者:liqijing <br>
     * 修改日期:2015-4-6下午07:29:49 <br>
     * E-mail: lijinginsistsmile@163.com <br>
     */
    @XmlType(name="Person",propOrder={"perId","perName","perAge","perSex","email"}) 
    public class Person {
    	
    	private String perId;
    	private String perName ;
    	private String perAge ;
    	private String perSex ;
    	private String email ;
    	
    	@XmlElement(name = "PerId")
    	public String getPerId() {
    		return perId;
    	}
    	public void setPerId(String perId) {
    		this.perId = perId;
    	}
    	
    	@XmlElement(name = "PerName")
    	public String getPerName() {
    		return perName;
    	}
    	public void setPerName(String perName) {
    		this.perName = perName;
    	}
    	
    	@XmlElement(name = "PerAge")
    	public String getPerAge() {
    		return perAge;
    	}
    	public void setPerAge(String perAge) {
    		this.perAge = perAge;
    	}
    	
    	@XmlElement(name = "PerSex")
    	public String getPerSex() {
    		return perSex;
    	}
    	public void setPerSex(String perSex) {
    		this.perSex = perSex;
    	}
    	
    	@XmlElement(name = "PerEmail")
    	public String getEmail() {
    		return email;
    	}
    	public void setEmail(String email) {
    		this.email = email;
    	}
    	
    	public Person() {
    		// TODO Auto-generated constructor stub
    	}
    	
    	public Person(String perId, String perName, String perAge, String perSex,String email) {
    		this.perId = perId;
    		this.perName = perName;
    		this.perAge = perAge;
    		this.perSex = perSex;
    		this.email = email ;
    	}
    	
    	
    }
    

    Body类:

    package com.insist.objectxml.person;
    
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    
    /**
     * 描述:body标头<br>
     * 作者:liqijing <br>
     * 修改日期:2015-4-6下午07:34:49 <br>
     * E-mail: lijinginsistsmile@163.com <br>
     */
    
    @XmlRootElement(name = "Body")
    public class Body {
    	
    	
    	private Person person ;
    
    	@XmlElement(name = "Person")
    	public Person getPerson() {
    		return person;
    	}
    
    	public void setPerson(Person person) {
    		this.person = person;
    	}
    	
    	
    }
    


    需要jar包:

    commons-lang3-3.1.jar

    slf4j-api-1.7.5-sources.jar

    slf4j-api-1.7.5.jar



    很高兴与你们分享:
       希望对需要实现 对象转XML或XML转对象的朋友们有帮助!
       谢谢!


    展开全文
  • public String toXml(Object root, String encoding, String declaration) { try { StringWriter writer = new StringWriter(); writer.append(declaration); createMarshaller(encoding, ...
    //测试类
    import com.toft.webservice.client.domino.DominoObject;
    import com.toft.webservice.core.JaxbBinder;
    
    
    public class JaxbTest {
    	
    	private static final String DECLARATION = "<?xml version='1.0' encoding='utf-8'?><!DOCTYPE document SYSTEM 'xmlschemas/domino_7_0_1.dtd'>";
    	private static final String ENCODING = "UTF-8";
    	private DominoObject dominoObject = new DominoObject();
    	public static void main(String[] args){
    		
    	}
    	
    	/**
    	 *  使用JAXB生成符合接口的XML.
    	 * @return String
    	 * @throws Exception
    	 */
    	private String getDominoXml() throws Exception {
    		try {
    			JaxbBinder binder = new JaxbBinder(DominoObject.class);
    			return binder.toXml(dominoObject, ENCODING, DECLARATION);
    		} catch (Exception e) {
    			throw e;
    		}
    	}
    }
    

    
    
     
    //工具类
    import java.io.StringReader;
    import java.io.StringWriter;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    
    /**
     * 使用Jaxb2.0实现XML<->Java Object的Binder.
     * 
     * @author 孙祖强
     */
    public class JaxbBinder {
    	//多线程安全的Context.
    	private JAXBContext jaxbContext;
    
    	/**
    	 * @param types 所有需要序列化的Root对象的类型.
    	 */
    	public JaxbBinder(Class<?>... types) {
    		try {
    			jaxbContext = JAXBContext.newInstance(types);
    		} catch (JAXBException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	/**
    	 * Java Object->Xml.
    	 */
    	public String toXml(Object root) {
    		try {
    			StringWriter writer = new StringWriter();
    			createMarshaller("UTF-8", null, true).marshal(root, writer);
    			return writer.toString();
    		} catch (JAXBException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	/**
    	 * Java Object->Xml.
    	 */
    	public String toXml(Object root, String encoding) {
    		try {
    			StringWriter writer = new StringWriter();
    			createMarshaller(encoding, null, false).marshal(root, writer);
    			return writer.toString();
    		} catch (JAXBException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	/**
    	 * Java Object->Xml.
    	 */
    	public String toXml(Object root, String encoding, String declaration) {
    		try {
    			StringWriter writer = new StringWriter();
    			writer.append(declaration);
    			createMarshaller(encoding, declaration, false).marshal(root, writer);
    			return writer.toString();
    		} catch (JAXBException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	/**
    	 * Xml->Java Object.
    	 */
    	@SuppressWarnings("unchecked")
    	public <T> T fromXml(String xml) {
    		try {
    			StringReader reader = new StringReader(xml);
    			return (T) createUnmarshaller().unmarshal(reader);
    		} catch (JAXBException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	/**
    	 * 创建Marshaller, 设定encoding(可为Null),  设定declaration(可为Null).
    	 */
    	public Marshaller createMarshaller(String encoding, String declaration, Boolean formatted) {
    		try {
    			Marshaller marshaller = jaxbContext.createMarshaller();
    
    			//是否格式化XML
    			if (formatted) {
    				marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    			}
    
    			//设置编码方式
    			if (null != encoding && !"".equals(encoding)) {
    				marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    			}
    
    			//设置XML声明
    			if (null != declaration && !"".equals(declaration)) {
    				marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
    			}
    			return marshaller;
    		} catch (JAXBException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	/**
    	 * 创建UnMarshaller.
    	 */
    	public Unmarshaller createUnmarshaller() {
    		try {
    			return jaxbContext.createUnmarshaller();
    		} catch (JAXBException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    }
    

    展开全文
  • XStream组件进行Object与XML互转用法 1.所需求jar包: xstream-1.3.1.jar 2.如果仅进行OBJECT与XML之间互转只需要这...2.XML转OBJECT XML 转OBJECT 只要调用xStream.fromXML(xml)方法,但同样要进行相关属性及类的映射。
  • ObjectToXml

    2018-08-01 10:55:13
    ObjectToXmlobject类型转换为xml类型,xml类型转换为object类型
  • XML转换成objectobject转换成XML

    千次阅读 2018-10-19 16:43:47
    1.转换代码如下 package ... import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import ja...

    1.转换代码如下

    package com.ihealthtek.jbagent.util;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    import java.io.*;
    
    /**
     * 封装了XML转换成object,object转换成XML的代码
     *
     * @author Steven
     *
     */
    public class XMLUtil {
        /**
         * 将对象直接转换成String类型的 XML输出
         *
         * @param obj
         * @return
         */
        public static String convertToXml(Object obj) {
            // 创建输出流
            StringWriter sw = new StringWriter();
            try {
                // 利用jdk中自带的转换类实现
                JAXBContext context = JAXBContext.newInstance(obj.getClass());
    
                Marshaller marshaller = context.createMarshaller();
                // 格式化xml输出的格式
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                        Boolean.TRUE);
                // 将对象转换成输出流形式的xml
                marshaller.marshal(obj, sw);
            } catch (JAXBException e) {
                e.printStackTrace();
            }
            return sw.toString();
        }
    
        /**
         * 将对象根据路径转换成xml文件
         *
         * @param obj
         * @param path
         * @return
         */
        public static void convertToXml(Object obj, String path) {
            try {
                // 利用jdk中自带的转换类实现
                JAXBContext context = JAXBContext.newInstance(obj.getClass());
    
                Marshaller marshaller = context.createMarshaller();
                // 格式化xml输出的格式
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                        Boolean.TRUE);
                // 将对象转换成输出流形式的xml
                // 创建输出流
                FileWriter fw = null;
                try {
                    fw = new FileWriter(path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                marshaller.marshal(obj, fw);
            } catch (JAXBException e) {
                e.printStackTrace();
            }
        }
    
        @SuppressWarnings("unchecked")
        /**
         * 将String类型的xml转换成对象
         */
        public static Object convertXmlStrToObject(Class clazz, String xmlStr) {
            Object xmlObject = null;
            try {
                JAXBContext context = JAXBContext.newInstance(clazz);
                // 进行将Xml转成对象的核心接口
                Unmarshaller unmarshaller = context.createUnmarshaller();
                StringReader sr = new StringReader(xmlStr);
                xmlObject = unmarshaller.unmarshal(sr);
            } catch (JAXBException e) {
                e.printStackTrace();
            }
            return xmlObject;
        }
    
        @SuppressWarnings("unchecked")
        /**
         * 将file类型的xml转换成对象
         */
        public static Object convertXmlFileToObject(Class clazz, String xmlPath) {
            Object xmlObject = null;
            try {
                JAXBContext context = JAXBContext.newInstance(clazz);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                FileReader fr = null;
                try {
                    fr = new FileReader(xmlPath);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                xmlObject = unmarshaller.unmarshal(fr);
            } catch (JAXBException e) {
                e.printStackTrace();
            }
            return xmlObject;
        }
    }
    

    2.

    package com.ihealthtek.jbagent.domain.in;
    
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import java.util.List;
    //最外层根节点
    @XmlRootElement(name="NETHIS")
    public class WnInArchiveList {
    
        List<WnInArchive> wnInArchives;
    //文件中的根标识
        @XmlElement(name = "GW")
        public List<WnInArchive> getWnInArchives() {
            return wnInArchives;
        }
    
        public void setWnInArchives(List<WnInArchive> wnInArchives) {
            this.wnInArchives = wnInArchives;
        }
    }
    
    3.
    package com.ihealthtek.jbagent.domain.in;
    
    import com.alibaba.fastjson.annotation.JSONField;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import java.io.Serializable;
    @XmlAccessorType(XmlAccessType.FIELD)
    // XML文件中的根标识
    @XmlRootElement(name = "GW")
    
    public class WnInArchive implements Serializable {
    
        /**
         *
         */
        @XmlElement(name = "GRBJH")
        private String grbjh;
       
        @XmlElement(name = "DABH")
        private String dabh;

    省略get set方法……

    }

     

    4.对象可以转换成xml格式String 

    String wnxml = XMLUtil.convertToXml(xxx);

    5.xml转换为对象

    WnOutArchiveList wn = (WnOutArchiveList)XMLUtil.convertXmlStrToObject(WnOutArchiveList.class,object);
    展开全文
  • xml object

    2017-02-28 13:37:02
    xml object
  • c# XML转JSON、JSON转XML,object转JSON

    万次阅读 2018-06-04 13:28:05
    public static string XmlTojson(this string s, string r = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") { s = s.Replace(r, ""); var doc = new XmlDocument(); ...

            public static string XmlTojson(this string s, string r = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") {

                s = s.Replace(r, "");
                var doc = new XmlDocument();
                doc.LoadXml(s);
                return JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);
            }

            public static string JsonToxml(this string s, string r = "root") {
                var doc = JsonConvert.DeserializeXmlNode(s, r);

                using (var stream = new MemoryStream()) {
                    var writer = new XmlTextWriter(stream, null) { Formatting = System.Xml.Formatting.Indented };
                    doc.Save(writer);

                    using (var sr = new StreamReader(stream, Encoding.UTF8)) {
                        stream.Position = 0;
                        return sr.ReadToEnd();
                    }
                }

            }

            public static string Json(this object o) {
                return new JavaScriptSerializer().Serialize(o);
            }

            public static object JsonParse(this string s) {
                return s.Trim().IsEmpty() ? new object() : new JavaScriptSerializer().Deserialize<object>(s);
            }

            public static bool IsJson(this string s) { try { JsonParse(s); return true; } catch { return false; } }

    展开全文
  • xml object 转换

    千次阅读 2015-04-06 13:53:32
    webservice传输数据格式是xml形式,可以使用本方案,xml模板配置一目了然。
  • Castor的使用,如何将java object转换为xml与将xml转换为java object
  • ObjectXML的相互转换

    千次阅读 2018-07-04 16:43:39
    JAXB(Java Architecture for XML Binding)能够帮助大家快速的进行ObjectXML进行相互映射,其中主要使用到的是JAXBcontext、Marshaller、Unmarshaller三个接口。 JAXBContext JAXBContext 类提供到 JAXB API ...
  • 前段时间找了好久xmlobject之间的转换都没找到!最近在学习WebService,讲到JAXB!没听说过!看了才知道jdk中自带了这个功能,什么这个框架那个框架都用了!原来就在眼前你也不知道!我这儿有视频,有需要请留言!...
  • Objectxml

    千次阅读 2018-05-25 10:27:48
    * Objectxml **/ public class XmlUtil { /** * xml文档Document对象 * * @param document * @param clazz * @return */ public static Object getObject (Document ...
  • objectxml的转换读取

    千次阅读 2015-03-05 17:15:15
    1.object ====> xml XmlDocument doc = new XmlDocument();  XmlElement Root = doc.CreateElement("Table"); //主内容  doc.AppendChild(Root); List eleColName=new List(); List eleValue=new List(); //
  • (数组 list集合 map集合 Object对象 XML数据格式) 成 string json
  • JAXB实现ObjectXML转换

    千次阅读 2014-05-05 13:43:23
    * XML转Object * @param * @param xmlStr * @param type * @return */ public static <T> T unmarshal(String xmlStr,Class<T> type){ T customer = null; try { JAXBContext ...
  • java中xmlobject(笔记)

    千次阅读 2017-02-10 17:47:54
    object转xml: 需要转换的object需要在类名上实现@XmlRootElement 解析的xml结构为    .... 如果需要别名,可以@XmlRootElement(name="别名") 属性别名,在属性的get方法上加上@XmlElement(name="别名")...
  • Spring 的Object/XML 映射支持Demo,spring结合第三方Castor Spring 3.0 的一个新特性是 O/X Mapper。O/X 映射器这个概念并不新鲜,O 代表 Object,X 代表 XML。它的目的是在 Java 对象(几乎总是一个 plain old ...
  • object to xml

    千次阅读 2014-05-06 12:06:43
    import java.util.ArrayList; import java.util.Iterator; import java.util.List;   ... * 根据该对象可以构造Xml字符串 ...public class XmlObject {   private static String HEAD = "
  • Jackson 实现Json、ObjectXml

    千次阅读 2018-05-18 02:07:15
    github 地址:https://github.com/FasterXML/jackson-dataformat-xml &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.dataformat&...jackson-dataformat-xml&lt;/artifa...
  • 因为是测试,所以是先从SD卡读取一个xml文件,转换成对象,再把这个对象生成xml文件,写入SD卡,(若是从服务器获取的,就可以直接使用返回的字符串了)  另外需要注意的问题就是编码,  先发测试xml文件。 /...
  • FirstObject XML

    2011-03-30 18:19:44
    FirstObject XML 2.1.4.416,单文件绿色版,一个非常好的XML解析修改工具
  • convertXML2Object 将对象转换为XML并将XML转换为NodeJS中的对象的示例
  • 这段时间在研究o/x mapping,即Java objectxml之间的转换以及xml文件验证的问题,自己也动手开发了一个小的演示例子,如下所示: --------开发环境----- 1.jdk1.5 2.jwsdp2.0(Java Web Services Developer ...
  • 主要介绍了详解XML,Object,Json转换与Xstream的使用的相关资料,需要的朋友可以参考下
  • xml和JAVA对象转换 simple-xml2object

    热门讨论 2013-03-20 14:16:02
    simple-xml2object是一个简单实用的xml和JAVA对象转换的类库,jar包很小,而且不需要任何依赖包。 下载后,压缩包包含一个jar包,导入即可。包含一个测试类,有详细的注释展示用法。还包含一个中文文档。
  • xml文件读取转换为Object,可用于游戏开发中
  • 对象转换xml

    2018-02-12 11:26:22
    winform窗口实现将XML文件内容转换成object对象类型,以及object对象转XML

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 733,094
精华内容 293,237
关键字:

object转xml