❶ 请问java中怎么将生成的XML转化为字符串
此方法传入文件名即可获得对象
-------------------------------------------
import java.beans.XMLDecoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class ReadXml {
public static Object getXml(String path){
File file=new File(path);
FileInputStream fileInputStream;
Object object=null;
try {
fileInputStream = new FileInputStream(file);
XMLDecoder decoder=new XMLDecoder(fileInputStream);
object=decoder.readObject();
fileInputStream.close();
decoder.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
}
---------------------------------------------------------------------
如果不可以 用这个写的方式 直接写对象到XML里 此方法需传入对象和写入路径
mport java.beans.XMLEncoder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteXml {
public static void setXml(Object o,String fileName){
File file=new File(fileName);
try {
FileOutputStream fileOutputStream=new FileOutputStream(file);
XMLEncoder encoder=new XMLEncoder(fileOutputStream);
encoder.writeObject(o);
encoder.flush();
encoder.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}