关于XML字符串和XML Document之间的转换

本文介绍如何在Java中将XML字符串与Java对象相互转换,包括使用JDOM、dom4j、原始的javax.xml.parsers及XStream等技术实现的具体方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在web项目中,XML作为一种重要的数据存储和传输介质,被广泛使用。XML文件,XML字符串和XML Document对象是XML存在的三种形式,XML文件无需多言,和普通的文本并无二致;倒是在做一般的XML数据交换过程中,经常要使用XML字符串和XML Document对象,因此在这两种形式之间进行转化成为了使用XML的必备技术。在所有操控XML的技术中,都提供了这两种形式XML之间的转换方法。
  下面我就各种XML技术对此问题的解决方法做个总结,和大家分享,也方便自己今后查阅。
一,使用JDOM(这是我最常使用的一种技术)
  1.字符串转Document对象
String xmlStr = ".....";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
Document doc = ( new SAXBuilder()).build(is);
  2.Document对象转字符串
Format format = Format.getPrettyFormat();
format.setEncoding( "gb2312"); //设置xml文件的字符为gb2312,解决中文问题
XMLOutputter xmlout = new XMLOutputter(format);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
xmlout.output(doc,bo);
String xmlStr = bo.toString();
 注:Document为org.jdom.Document

二,使用最原始的javax.xml.parsers,标准的jdk api
  1.字符串转Document对象
String xmlStr = "......";
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(is);
  2.Document对象转字符串
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty( "encoding", "GB23121"); //解决中文问题,试过用GBK不行
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform( new DOMSource(doc), new StreamResult(bos));
String xmlStr = bos.toString();
 注:Document为org.w3c.dom.Document

三,使用dom4j(这是最简单的方法)
  1.字符串转Document对象
String xmlStr = "......";
Document document = DocumentHelper.parseText(xmlStr);
  2.Document对象转字符串
Document document = ...;
String text = document.asXML();
 注:Document为org.dom4j.Document

四,在JavaScript中的处理
 1.字符串转Document对象
var xmlStr = ".....";
var xmlDoc = new ActiveXObject( "Microsoft.XMLDOM");
xmlDoc.async= false;
xmlDoc.loadXML(xmlStr);
//可以处理这个xmlDoc了
var name = xmlDoc.selectSingleNode( "/person/name");
alert(name.text);
  2.Document对象转字符串
var xmlDoc = ......;
var xmlStr = xmlDoc.xml
 注:Document为javaScript版的XMLDOM

本文出自 “夜狼” 博客,请务必保留此出处http://yangfei520.blog.51cto.com/1041581/382977

 

xml格式字符串与java对象互转

Java代码 复制代码  收藏代码
  1. import java.lang.reflect.Field;   
  2. import java.util.List;   
  3.   
  4. import com.thoughtworks.xstream.XStream;   
  5.   
  6. public class XmlUtil {   
  7.     // 所有需要注册的类的配置,   
  8.     public static final String CONFIGFILE = new GetClassPath()   
  9.             .getMyConfigPath()   
  10.             + "/xml.prop";   
  11.        
  12.     private static XStream xs = null;   
  13.        
  14.     private static XmlUtil xmlUtil = null;   
  15.   
  16.     private XmlUtil() {   
  17.         try {   
  18.             // 获取所有需要与处理的java完整名   
  19.             List list = FileUtil.readFile(CONFIGFILE);   
  20.                
  21.             //初始化xs   
  22.             xs = alias(list);   
  23.         } catch (ClassNotFoundException e) {   
  24.             e.printStackTrace();   
  25.         }   
  26.     }   
  27.        
  28.     /**  
  29.      * 获得实例  
  30.      * @return  
  31.      */  
  32.     public static synchronized XmlUtil getInstance() {   
  33.            
  34.         if(null == xmlUtil){   
  35.             xmlUtil = new XmlUtil();   
  36.         }   
  37.            
  38.         return xmlUtil;   
  39.     }   
  40.   
  41.     /**  
  42.      * 根据类名做反射  
  43.      *   
  44.      * @param list  
  45.      *            类完整名  
  46.      * @return  
  47.      * @throws ClassNotFoundException  
  48.      */  
  49.     public XStream alias(List list) throws ClassNotFoundException {   
  50.         XStream xs = new XStream();   
  51.         for (int i = 0; i < list.size(); i++) {   
  52.             Object obj;   
  53.             try {   
  54.                 obj = Class.forName((String) list.get(i)).newInstance();   
  55.                 Class zz = obj.getClass();   
  56.                 aliasAtt(xs, zz);   
  57.             } catch (InstantiationException e) {   
  58.                 e.printStackTrace();   
  59.             } catch (IllegalAccessException e) {   
  60.                 e.printStackTrace();   
  61.             }   
  62.         }   
  63.         return xs;   
  64.     }   
  65.   
  66.     /**  
  67.      * 对类进行xml解析配置  
  68.      *   
  69.      * @param xs  
  70.      * @param z  
  71.      *            class对象  
  72.      */  
  73.     public void aliasAtt(XStream xs, Class z) {   
  74.         if (null == z) {   
  75.             return;   
  76.         }   
  77.   
  78.         // 类名注册   
  79.         xs.alias(z.getSimpleName(), z);   
  80.         Field[] field = z.getDeclaredFields();   
  81.         // 类中成员变量注册,继承的不注册   
  82.         for (int i = 0; i < field.length; i++) {   
  83.             xs.aliasField(field[i].getName(), z, field[i].getName());   
  84.         }   
  85.     }   
  86.        
  87.     /**  
  88.      * xml 格式字符串转换为对象  
  89.      * @param str  
  90.      * @return  
  91.      */  
  92.     public Object xmlToObject(String str) {   
  93.         return xs.fromXML(str);   
  94.     }   
  95.        
  96.     /**  
  97.      * 对象转换为xml格式字符串  
  98.      * @param obj  
  99.      * @return  
  100.      */  
  101.     public String objToXml(Object obj) {   
  102.         return xs.toXML(obj);   
  103.     }   
  104. }   
  105.   
  106. FileUtil.readFile()方法如下   
  107.   
  108. /**  
  109.      * 读取文件  
  110.      *   
  111.      * @param filePath  
  112.      *            文件完整名  
  113.      * @return 文件内容  
  114.      * @throws IOException  
  115.      */  
  116.     public static List readFile(String filePath) {   
  117.   
  118.         List list = new ArrayList();   
  119.   
  120.         FileInputStream fs = null;   
  121.         InputStreamReader isr = null;   
  122.         BufferedReader br = null;   
  123.   
  124.         try {   
  125.             fs = new FileInputStream(filePath);   
  126.   
  127.             isr = new InputStreamReader(fs);   
  128.   
  129.             br = new BufferedReader(isr);   
  130.   
  131.             String data = "";   
  132.             while ((data = br.readLine()) != null) {   
  133.                 list.add(data.trim());   
  134.             }   
  135.         } catch (IOException e) {   
  136.             e.printStackTrace();   
  137.         } finally {   
  138.             try {   
  139.                 if (br != null)   
  140.                     br.close();   
  141.                 if (isr != null)   
  142.                     isr.close();   
  143.   
  144.                 if (fs != null)   
  145.                     fs.close();   
  146.   
  147.             } catch (IOException e) {   
  148.                 e.printStackTrace();   
  149.             }   
  150.         }   
  151.   
  152.         return list;   
  153.     }   
  154.   
  155. Test   
  156.          Printdata pd = new Printdata();   
  157.     pd.setPrintFileList(printFileList);   
  158.     pd.setAuto("1");   
  159.     pd.setBillReceiver("billReceiver");   
  160.     pd.setCustId("cust_id");   
  161.     pd.setYear("2011");   
  162.     pd.setMonth("11");   
  163.     List list = FileUtil.readFile(XmlUtil.CONFIGFILE);   
  164.     XmlUtil xmlUtil = XmlUtil.getInstance();   
  165.     String xml = xmlUtil.objToXml(pd);//对象至xml   
  166.     System.out.println(xml);   
  167.          Printdata obj = (Printdata)xmlUtil.xmlToObject(xml);//xml至对象  
import java.lang.reflect.Field;
import java.util.List;

import com.thoughtworks.xstream.XStream;

public class XmlUtil {
	// 所有需要注册的类的配置,
	public static final String CONFIGFILE = new GetClassPath()
			.getMyConfigPath()
			+ "/xml.prop";
	
	private static XStream xs = null;
	
	private static XmlUtil xmlUtil = null;

	private XmlUtil() {
		try {
			// 获取所有需要与处理的java完整名
			List list = FileUtil.readFile(CONFIGFILE);
			
			//初始化xs
			xs = alias(list);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获得实例
	 * @return
	 */
	public static synchronized XmlUtil getInstance() {
		
		if(null == xmlUtil){
			xmlUtil = new XmlUtil();
		}
		
		return xmlUtil;
	}

	/**
	 * 根据类名做反射
	 * 
	 * @param list
	 *            类完整名
	 * @return
	 * @throws ClassNotFoundException
	 */
	public XStream alias(List list) throws ClassNotFoundException {
		XStream xs = new XStream();
		for (int i = 0; i < list.size(); i++) {
			Object obj;
			try {
				obj = Class.forName((String) list.get(i)).newInstance();
				Class zz = obj.getClass();
				aliasAtt(xs, zz);
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return xs;
	}

	/**
	 * 对类进行xml解析配置
	 * 
	 * @param xs
	 * @param z
	 *            class对象
	 */
	public void aliasAtt(XStream xs, Class z) {
		if (null == z) {
			return;
		}

		// 类名注册
		xs.alias(z.getSimpleName(), z);
		Field[] field = z.getDeclaredFields();
		// 类中成员变量注册,继承的不注册
		for (int i = 0; i < field.length; i++) {
			xs.aliasField(field[i].getName(), z, field[i].getName());
		}
	}
	
	/**
	 * xml 格式字符串转换为对象
	 * @param str
	 * @return
	 */
	public Object xmlToObject(String str) {
		return xs.fromXML(str);
	}
	
	/**
	 * 对象转换为xml格式字符串
	 * @param obj
	 * @return
	 */
	public String objToXml(Object obj) {
		return xs.toXML(obj);
	}
}

FileUtil.readFile()方法如下

/**
	 * 读取文件
	 * 
	 * @param filePath
	 *            文件完整名
	 * @return 文件内容
	 * @throws IOException
	 */
	public static List readFile(String filePath) {

		List list = new ArrayList();

		FileInputStream fs = null;
		InputStreamReader isr = null;
		BufferedReader br = null;

		try {
			fs = new FileInputStream(filePath);

			isr = new InputStreamReader(fs);

			br = new BufferedReader(isr);

			String data = "";
			while ((data = br.readLine()) != null) {
				list.add(data.trim());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
				if (isr != null)
					isr.close();

				if (fs != null)
					fs.close();

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return list;
	}

Test
         Printdata pd = new Printdata();
	pd.setPrintFileList(printFileList);
	pd.setAuto("1");
	pd.setBillReceiver("billReceiver");
	pd.setCustId("cust_id");
	pd.setYear("2011");
	pd.setMonth("11");
	List list = FileUtil.readFile(XmlUtil.CONFIGFILE);
	XmlUtil xmlUtil = XmlUtil.getInstance();
	String xml = xmlUtil.objToXml(pd);//对象至xml
	System.out.println(xml);
         Printdata obj = (Printdata)xmlUtil.xmlToObject(xml);//xml至对象


需要的jar包见附件

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值