❶ 請問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();
}
}
}