序列化XML到字符串

时间:2014-09-26 17:17:44

标签: java xml serializer

我生成这样的XML。它工作正常。但我想在Eliscps中打印出来:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class PersonConstructor {
    String info="";
    String path="c://myfile/myperson";

    // here is my xml object
    Person person = new Person();
    person.setFirstName("fname");
    person.setLastName("lname");
    person.setTel("111-111-1111");
    person.setAddress("1000 main st.");

    //Serializer my object to file.
    Serializer serializer = new Persister();
    File file = new File(path);
    serializer.write(person, file);

    //now I want to print out my xml file.I don't know how to do it.
    info = file.toString();
    System.out.println(info);
}

我应该使用输出流吗?

1 个答案:

答案 0 :(得分:0)

使用缓冲读卡器。只需确保将IOException添加到方法签名或使用try / catch块包围。

BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line != null)
{
    System.out.println(line);
    line = in.readLine();
}
in.close();