[英]Java JAXB unmarshaller linked exception
背景:我正在嘗試使用JAXB解組器將XML解析為對象。
完成的工作:我使用JAXB本身來生成對象類,並編寫了一些方法來解組xml。
public void xmlParser() {
try {
Acquirer acquirer = (Acquirer) readXml(Constants.XML_PATH);
System.out.println(acquirer.getDate());
} catch (JAXBException | IOException e) {
e.printStackTrace();
}
}
/**
* Initializes of JAXB Context and Unmarshaller.
*/
private static void createContext() {
try {
jaxbContext = JAXBContext.newInstance("com.test.xml.generated");
unmarshaller = jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
e.printStackTrace();
}
}
/**
* This reads the XML file from the resources in ClassPath.
*
* @param xmlFile XML file name as String with relative ClassPath
* @return Unmarashalled XML file
* @throws JAXBException
* @throws IOException
* @throws Exception
*/
public Object readXml(String xmlFile) throws JAXBException, IOException {
if (jaxbContext == null) {
createContext();
}
InputStream stream = getClass().getClassLoader().getResourceAsStream(xmlFile);
BufferedInputStream buffredStream = new BufferedInputStream(stream);
***Error:***
Object obj = unmarshaller.unmarshal(buffredStream);
buffredStream.close();
stream.close();
return obj;
}
對象obj中有錯誤 。
例外:
javax.xml.bind.UnmarshalException - with linked exception:
[java.io.IOException: Stream closed]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:125)
我已經設法搜索的內容:我使用xml驗證程序來驗證xml,這看起來還不錯。 我還看到有人建議不要使用InputStream等。因此,我嘗試使用File file = new File();。 沒有。 此外,我嘗試檢查自動生成的對象類,但沒有發現任何可疑的東西。 @XmlElement和Root似乎定義得很好。
PS我有此xml的xsd方案(我使用此xsd生成了所有對象類)。 我什至使用在線工具來驗證它們,一切似乎都正確。
Constants.XML_PATH =“ /Acquirer.xml”;
只需更改:
InputStream stream = getClass().getClassLoader().getResourceAsStream(xmlFile);
上:
InputStream stream = getClass().getResourceAsStream(xmlFile);
因為當您使用getClass().getClassLoader().getResourceAsStream(xmlFile)
它將返回null
(找不到資源),並且在向構造函數中提供null
而不是輸入流實例時, BufferedInputStream
會引發IOException
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.