如何在执行编组程序时解决异常“方法编组(Book,> FileWriter)未定义类型Pool.Marshaller”。
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import com.sun.xml.internal.ws.util.Pool.Marshaller;
public class BookMarshaller {
public static void main(String[] args) {
try {
Book book = new Book("9780312347482", "Power Play", "Joseph Finder");
FileWriter writer = new FileWriter("book.xml");
Marshaller.marshal(book, writer);
List book2Authors = new ArrayList();
book2Authors.add("Douglas Preston");
book2Authors.add("Lincoln Child");
Book book2 = new Book("9780446618502", "The Book of the Dead",
book2Authors);
writer = new FileWriter("book2.xml");
Marshaller.marshal(book2, writer);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace(System.err);
}
}
}
答案 0 :(得分:0)
您正在使用com.sun.xml.ws.util.Pool.Marshaller
- 我想,您想要使用javax.xml.bind.Marshaller
。 验证更改您的import语句!
Pool.Marshaller
没有marshal
方法。
和 - 就像skaffman在他的评论中指出的那样 - marshal
不是一个静态方法 - 你需要一个JAXB上下文来创建一个marshaller实例来编组图书实例。
答案 1 :(得分:0)
我建议您将代码更改为以下内容:
package forum9736839;
import java.io.FileWriter;
import java.util.*;
import javax.xml.bind.*;
public class BookMarshaller {
public static void main(String[] args) {
try {
JAXBContext jc = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jc.createMarshaller();
Book book = new Book("9780312347482", "Power Play", "Joseph Finder");
FileWriter writer = new FileWriter("book.xml");
marshaller.marshal(book, writer);
List book2Authors = new ArrayList();
book2Authors.add("Douglas Preston");
book2Authors.add("Lincoln Child");
Book book2 = new Book("9780446618502", "The Book of the Dead",
book2Authors);
writer = new FileWriter("book2.xml");
marshaller.marshal(book2, writer);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace(System.err);
}
}
}