我在各种堆栈溢出帖子和博客条目中看到了以下语法:
JAXBElement<SomeClass> sc = unmarshaller.unmarshal(is, SomeClass.class);
那么为什么当我尝试使用这种语法时,eclipse会给我一个编译错误?为什么这个语法不在api中,你可以阅读at this link?
以下是编译错误:
The method unmarshal(Node, Class<T>) in the type Unmarshaller
is not applicable for the arguments (FileInputStream, Class<SomeClass>)
这是一个使用上述语法的完整方法:
public void unmarshal() throws FileNotFoundException{
Unmarshaller unmarshaller;
try {
JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
unmarshaller = ctx.createUnmarshaller();
FileInputStream is = new FileInputStream("path/to/some.xml");
JAXBElement<SomeClass> sc = unmarshaller.unmarshal(is, SomeClass.class);//error here
System.out.println("title is: "+sc.getValue().getTitle());
} catch (JAXBException e) {e.printStackTrace();}
}
这个语法在开发人员需要解组不包含已定义根元素的xml的示例中给出。一个例子是Sayantam的回答to this question。
答案 0 :(得分:2)
错误是由于错误的类型参数,FileInputStream而不是Node。
此方法更适合解组一部分xml。如果要解析整个文件,请使用unsmarshal(File)方法。
public void unmarshal() throws FileNotFoundException{
Unmarshaller unmarshaller;
try {
JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
unmarshaller = ctx.createUnmarshaller();
FileInputStream is = new FileInputStream("path/to/some.xml");
SomeClass sc = (SomeClass) unmarshaller.unmarshal(is);
System.out.println("title is: "+sc.getValue().getTitle());
} catch (JAXBException e) {e.printStackTrace();}
}
如果你不想演员,请试试这个:
public void unmarshal() throws FileNotFoundException{
Unmarshaller unmarshaller;
try {
JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
unmarshaller = ctx.createUnmarshaller();
XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
StreamSource streamSource = new StreamSource("path/to/some.xml");
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(streamSource);
JAXBElement<SomeClass> sc = unmarshaller.unmarshal(xmlStreamReader, SomeClass.class);//error here
System.out.println("title is: "+sc.getValue().getTitle());
} catch (JAXBException e) {e.printStackTrace();}
}