背景:我正在尝试使用 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;
}
错误在对象对象中.....
例外:
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";
眼眸繁星
相关分类