咋成这样了啊?
package com.accp.xml;
import nu.xom.*;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class Person {
private String first, last;
public Person(String first, String last) {
this.first = first;
this.last = last;
}
public Element getXML() {
Element person = new Element("person");
Element firstName = new Element("first");
firstName.appendChild(first);
Element lastName = new Element("last");
lastName.appendChild(last);
person.appendChild(firstName);
person.appendChild(lastName);
return person;
}
public Person(Element person) {
first = person.getFirstChildElement("first").getValue();
last = person.getFirstChildElement("last").getValue();
}
public String toString() {
return first + " " + last;
}
public static void format(OutputStream os, Document doc) {
try {
Serializer serializer = new Serializer(os, "ISO-8859-1");
serializer.setIndent(4);
serializer.setMaxLength(60);
serializer.write(doc);
serializer.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
List<Person> people=Arrays.asList(
new Person("Dr. Bunsen", "Honeydew"),
new Person("Gonzo", "The Great"),
new Person("Phillip j.", "Fry"));
System.out.println(people);
Element root=new Element("person");
for(Person p : people){
System.out.println(p+" 对象");
root.appendChild(p.getXML());
Document doc=new Document(root);
format(System.out, doc);
try {
format(new BufferedOutputStream(new FileOutputStream("People.xml")),doc);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
这个是要读的XML文档
<?xml version="1.0" encoding="UTF-8"?>
<people>
<person>
<first>Dr. Bunsen</first>
<last>Honeydew</last>
</person>
<person>
<first>Gonzo</first>
<last>The Great</last>
</person>
<person>
<first>Phillip j.</first>
<last>Fry</last>
</person>
</people>
放在了循环外面,还有JAR包导入也出错了,把jar包重新导入了,可以了,但是这个代码我不知道它的意思可以详细的加注释解说一下吗? |