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++;
}
}