---
title: "对象转xml变成string返回"
author: "弦上的福音"
date: "2014-03-21T11:14:10Z"
tags: []
slug: "xml-string"
draft: false
lastmod: "2014-03-21T11:14:10Z"
id: 2034432
url: "https://1574468392.iteye.com/blog/2034432"
---

```
/**
	 * 将对象转换成String
	 * @param obj
	 * @return
	 */
	public String xmlChangeToString(List<ArhtInputTerObj> obj) {
		StringBuffer sb = new StringBuffer();
		try {
			File file = new File("C:\\sybuildSchemeTemp.xml");
			FileOutputStream fos = new FileOutputStream(file);
			XMLEncoder encoder = new XMLEncoder(fos);
			encoder.writeObject(obj);
			encoder.flush();
			encoder.close();
			fos.close();

			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			int tempc = 0;
			while ((tempc = isr.read()) != -1) {
				sb.append((char) tempc);
			}
			isr.close();
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return sb.toString();
	}
	/**
	 * 将String转换成对象
	 * @param obj
	 * @return
	 */
	public List<ArhtInputTerObj> xmlChangeToXMLData(String xmlString) {
		List<ArhtInputTerObj> xmlData = null;
		try {
			File file = new File("C:\\sybuildXMLDataTemp.xml");
			FileOutputStream fos = new FileOutputStream(file);
			OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
			writer.write(xmlString);
			writer.close();

			FileInputStream ins = new FileInputStream(file);
			XMLDecoder xMLDecoder = new XMLDecoder(ins, "UTF-8");
			xmlData = (List<ArhtInputTerObj>) xMLDecoder.readObject();
			ins.close();
			xMLDecoder.close();
			xmlString = null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xmlData;
	}
```