Skip to main content
 首页 » 编程设计

xml-parsing之使用 JAXB 和 Unmarshaller 过早结束文件。响应中的 xml 对我来说看起来有效

2024年05月29日31langtianya

我不知道该怎么办了。一切看起来都是正确的;输入输出。

我生成 xml 文件并发送到某些服务进行验证。

响应是:

11:10:34,922 INFO  [STDOUT] printing out the input stream 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Response> 
    <Method name="XML/Release/New" time="2013-04-23T15:10:35.1446238Z"> 
        <ResponseStatus>100</ResponseStatus> 
    </Method> 
</Response> 
finished printing out the input stream 
11:10:34,922 INFO  [STDOUT] got the unmarshaller 
11:10:34,925 ERROR [PRNDataAccessUtil] Caught an error: javax.xml.bind.UnmarshalException 
 - with linked exception: [org.xml.sax.SAXParseException: Premature end of file.] : null 

代码:

try { 
            out = connection.getOutputStream(); 
            ByteArrayOutputStream bos = PRNPostNewsReleaseUtil.createNewsReleaseXml(newsRelease); 
            bos.writeTo(out); 
 
            JAXBContext context = JAXBContext.newInstance(Response.class.getPackage().getName()); 
            in = connection.getInputStream(); 
 
            BufferedReader inp = new BufferedReader(new InputStreamReader(in)); 
            System.out.println("printing out the input stream"); 
            String line; 
            while((line = inp.readLine()) != null) { 
                System.out.println(line); 
            } 
            System.out.println("finished printing out the input stream"); 
 
            Unmarshaller unmarshaller = context.createUnmarshaller(); 
            response = (Response) unmarshaller.unmarshal(in); 
 
        } catch (Exception ex) { 
            log.error("Caught an error: " + ex + " : " + ex.getMessage()); 
            return null; 
        } finally { 
            if (null != in) connection.disconnect(); 
        } 

请您参考如下方法:

您收到错误是因为 InputStream 在输出过程中已提前到末尾。假设 BufferedReader 中的缓冲区足够大,可以容纳整个 XML 文档,您可以在输出后重置它,然后对其进行解码。