java 使用 JAXB 解析响应 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4465092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing Response XML with JAXB
提问by bmw0128
I want to read a response from a non-wsdl web service call using JAXB. I am sending a POST request using HttpURLConnection, and getting a response. My question is do I make an xml doc from the response stream, then use jaxb to make the java objects? Or, is it possible to use use jaxb on the fly with the response stream? This will be a web application, and I will not be able to store a generated xml doc anywhere, so if i need to make an xml doc, how do i store it for jaxb to use, if I cannot do the jaxb on the fly?
我想使用 JAXB 读取来自非 wsdl Web 服务调用的响应。我正在使用 HttpURLConnection 发送 POST 请求,并获得响应。我的问题是我是否从响应流中创建一个 xml 文档,然后使用 jaxb 来创建 java 对象?或者,是否可以在响应流中即时使用 jaxb?这将是一个 Web 应用程序,我将无法在任何地方存储生成的 xml 文档,所以如果我需要制作一个 xml 文档,如果我不能即时执行 jaxb,我该如何存储它以供 jaxb 使用?
采纳答案by sblundy
The Unmarshaller.unmarshal
can take an InputStream, which would eliminated the need to parse it to an XML doc.
该Unmarshaller.unmarshal
可以采取一个InputStream,这将消除需要将其解析到一个XML文档。
回答by bdoughan
Here is an example:
下面是一个例子:
String uri =
"http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer =
(Customer) jc.createUnmarshaller().unmarshal(xml);
connection.disconnect();
For more information see:
有关更多信息,请参阅: