gpt4 book ai didi

java - Unmarshaller.unmarshal() 的二元形式

转载 作者:行者123 更新时间:2023-11-30 03:42:32 34 4
gpt4 key购买 nike

我在各种堆栈溢出帖子和博客条目中看到了以下语法:

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 .

最佳答案

该错误是由于错误的类型参数引起的,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();}
}

关于java - Unmarshaller.unmarshal() 的二元形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26498474/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com