1つのタグだけを表示するために、RESTベースのサービスにアクセスして返されたXMLデータを解析する必要があります。たとえば、以下のXMLデータを解析して、firstnameタグとvalue Johnのみを表示します。RESTClientがXMLデータを返した後のSaxParserコードとのインターフェイス方法
XMLデータがRESTClientによって返されると、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