我需要解析从访问基于REST的服务返回的XML数据,以仅显示一个标签。例如,解析下面显示的XML数据以仅显示名字标记和值John。如何在RESTClient返回XML数据后与SaxParser代码进行交互?
<company>
<staff>
<firstname>John</firstname>
<lastname>Doe</lastname>
</staff>
</company>
我一直在努力弄清楚一旦RESTClient返回XML数据后,如何与SAX解析代码进行接口。在学习了不同的示例代码后,我尝试了不同的方法,但仍然无法部分解读它,因为它们没有相同的确切目的。所以,请教我如何调用/将数据传递给解析代码以及从解析代码返回的内容,解析代码是否应该放在单独的类中,等等。我基本上没有一些指导就无能为力。相关的RESTClient代码如下所示。谢谢!
public class RESTClient {
public static String callRESTService(String url) {
String result = null;
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
InputStream instream = entity.getContent();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp;
try (
sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
DefaultHandler handler = new DefaultHandler();
xr.setContentHandler(handler);
InputSource is = new InputSource(instream);
xr.parse(is);
//what should/can be returned here from the parsing code:
//String, InputSource, InputStream?. Convert data type?
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
)
你必须实现你自己的'DefaultHandler' – zapl 2012-03-21 09:36:51