如何使用 XStream 类库在屏幕终端上打印 XML?
我需要打印
System.out.println(recordXML.read());
但它返回:
<list><registrosarraylist02xml.Pessoas><ID>1</ID><nome>Regis</nome><idade>25</idade></registrosarraylist02xml.Pessoas><registrosarraylist02xml.Pessoas><ID>2</ID><nome>Rose</nome><idade>32</idade></registrosarraylist02xml.Pessoas><registrosarraylist02xml.Pessoas><ID>3</ID><nome>david</nome><idade>10</idade></registrosarraylist02xml.Pessoas></list>
我想打印类似于:
System.out.println(p.ID + " - " + p.name + " - " + p.age);
ID - 姓名 - 年龄 1 - 里吉斯 - 25
2 - 玫瑰 - 32
3 - 大卫 - 10
import com.thoughtworks.xstream.XStream;
import java.util.ArrayList;
import java.util.Scanner;
public class RegistrosArrayList02_xml {
public static void main(String[] args) {
ArrayList listPerson = new ArrayList();
recordXML(listPerson);
show(listPerson);
static void show(ArrayList mylist) {
System.out.println("ID - name - age");
for (int i = 0; i < mylist.size(); i++) {
Person p = (Person) mylist.get(i);
System.out.println(p.ID + " - " + p.name + " - " + p.age);
}
}
static void recordXML(ArrayList mylist) {
XStream xstream = new XStream();
String xml = xstream.toXML(mylist);
RecordRead record = new RecordRead();
RecordRead.record(xml);
}
}
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class RecordRead {
static void record(String xml) {
try {
FileWriter w = new FileWriter("teste.xml");
w.write(xml);
w.close();
} catch (Exception e) {
System.out.println("Error record XML: " + e);
}
}
static String read() {
try {
Scanner in = new Scanner(new File("teste.xml"));
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
sb.append(in.next());
}
in.close();
return sb.toString();
} catch (Exception e) {
System.out.println("Error read XML: " + e);
}
return "";
}
}
public class Person {
public static int lastID = 1;
public int ID;
public String name;
public int age;
public Person() {
ID = Person.lastID++;
}
}